/************************************************************
 *  * EaseMob CONFIDENTIAL
 * __________________
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of EaseMob Technologies.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from EaseMob Technologies.
 */

#define HEADHIGH 50//头部view高度
#import <AVFoundation/AVFoundation.h>
#import "ChatViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "WEBViewController.h"
#import "FriendsViewController.h"
#import "SRRefreshView.h"
#import "DXChatBarMoreView.h"
#import "DXRecordView.h"
#import "DXFaceView.h"
#import "EMChatViewCell.h"
#import "EMChatTimeCell.h"
#import "ChatSendHelper.h"
#import "MessageReadManager.h"
#import "MessageModelManager.h"
#import "LocationViewController.h"
#import "ChatGroupDetailViewController.h"
#import "UIViewController+HUD.h"
#import "NSDate+Category.h"
#import "DXMessageToolBar.h"
#import "DXChatBarMoreView.h"
#import "ChatViewController+Category.h"
#import "EMCDDeviceManager.h"
#import "EMCDDeviceManagerDelegate.h"
#import "AudioToolbox/AudioToolbox.h"//震动
#import "HttpPostExecutor.h"
#import "ChatSendHelper.h"
#import "EMChatNotiCell.h"
#import "EMAlertView.h"
#import "MLUserDataViewController.h"
#import "MenuView.h"
#import "PayViewController.h"
#import "GiftViewController.h"
#import "ChatGiftTableViewCell.h"
#import "ReportUploadImageViewController.h"
#define KPageCount 20
#define KHintAdjustY    50

//#define kTestChatTimeCount 20
//#define kChatOverTime 30
//#define kLoveAddTime 10

//#define kBuyLabelText @"领走虚拟恋人"
//#define kBuyLabelTextChat @"聊天时间已经用完，领走恋人才可以继续聊天打电话哦"
//#define kBuyLabelTextTestChat @"每天1次的试聊机会已经用完，领走恋人才可以继续聊天哦"
//typedef NS_ENUM(NSInteger, ChatType) {
//    ChatType_NORMAL_AND_NORMAL = 0,//普通情况,双方都是普通人
//    ChatType_NORMAL_AND_LOVE = 1,//我是普通人,对方是恋人
//    ChatType_LOVE_AND_NORMAL = 2,//我是恋人,对方是普通人
//    ChatType_LOVE_AND_LOVE = 3, //我是恋人,对方也是恋人
//    
//};
////处理复杂问题,先复杂化,再优化
//typedef NS_ENUM(NSInteger, ChatStatus){
//    ChatStatus_NO = 0,  //网络错误
//    ChatStatus_NONE = 1,//可以聊天状态,(双方都是普通人)
//    //我时普通人,对方恋爱体验师
//    ChatStatus_TEST_CHAT = 2,//今天有试聊的机会,如果发送消息,则使用掉今天的试聊机会,
//    ChatStatus_timeView_SHOW = 3,//没有试聊机会,,需要弹框购买时间的
//    ChatStatus_TEST_CHAT_OVERTIME = 4,//试聊超时,修改状态
//    ChatStatus_TEST_CHAT_GOING = 5,//试聊正在进行,有试聊时间
//    ChatStatus_TEST_CHAT_ORDER_BEGIN = 6, // 正在创建试聊,创建成功,修改为可以聊天状态(),正在创建也是这个状态,创建失败,重新创建试聊单(ChatStatus_TEST_CHAT),无网络提示网络错误
//    ChatStatus_TEST_CHAT_WAUT_BEGIN = 7,//试聊正在等待开始
//    //    ChatStatus_TEST_CHAT_WAUT_OVERTIME = 8,//试聊等待超时,修改试聊状态
//    ChatStatus_CHAT_ORDER_OVERTIME = 9,//正式的聊天订单超时
//    ChatStatus_CHAT_ORDER_WAUT = 10,//聊天订单等待开始
//    ChatStatus_CHAT_ORDER_GOING = 11,//聊天正在进行中
//    ChatStatus_NORMAL_LOVE_OVERTIME = 12,//聊天是爱心加时
//    //我时恋爱体验师,对方普通人
//    ChatStatus_TEST_CHAT_LOVE_WAUT = 20,//有试聊订单,进入等待情况,发送消息开始订单,等待超时则进入超时状态,不能发送消息
//    ChatStatus_TEST_CHAT_LOVE_WAUT_SEND = 21,//发送消息的时候创建订单的等待时间,如果成功,如果失败
//    ChatStatus_TEST_CHAT_LOVE_GOING = 22,//试聊订单开始了
//    //    ChatStatus_TEST_CHAT_LOVE_OVERTIME = 23,//长时间未回复试聊订单已经超时
//    ChatStatus_TEST_CHAT_LOVE_END = 24,//试聊结束了时间到了
//    ChatStatus_CHAT_ORDER_LOVE_OVERTIME = 25, // 聊天订单长时间没有回复,订单取消
//    ChatStatus_CHAT_ORDER_LOVE_WAUT = 26,//聊天订单等待开始
//    ChatStatus_CHAT_ORDER_LOVE_WAUT_SEND = 27,//聊天订单开始发送消息,等待创建订单
//    ChatStatus_CHAT_ORDER_LOVE_GOING = 28,//聊天订单开始了
//    ChatStatus_NO_Order = 30,//对方和你没有聊天订单
//    
//    
//    //我是恋爱体验师,对方也是恋爱体验师
//    ChatStatus_LAL_TEST_CHAT_CHANCE = 50,//我有试聊机会
//    ChatStatus_LAL_TEST_CHAT_CHANCE_SET = 51,//正在创建试聊订单,创建成功ChatStatus_LAL_TEST_CHAT_WAUT,失败ChatStatus_LAL_TEST_CHAT_CHANCE
//    ChatStatus_LAL_TEST_CHAT_CHANCE_NO = 52,//我没有试聊机会
//    ChatStatus_LAL_TEST_CHAT_WAUT = 53,//试聊等待开始
//    ChatStatus_LAL_TEST_CHAT_REPLY = 54, //试聊订单进入等待回复,发出消息就进入成功回复,开始试聊订单
//    ChatStatus_LAL_TEST_CHAT_WAUT_BEGIN = 55,//有对方的试聊订单,并且正在开始还没用超时
//    ChatStatus_LAL_TEST_CHAT_WAUT_OVERTIME = 55,//有对方的试聊订单,但是已经超时了
//    
//    ChatStatus_Sweetheart_NO = 60 ,//对方恋人已满,请返回重试
//    
//    ChatStatus_TIME_END = 99,//时间结束,弹出续时框
//    
//    
//    ChatStatus_WAIT = 100,//正在查询聊天权限,请稍后
//    
//};

@interface ChatViewController ()<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, SRRefreshDelegate, IChatManagerDelegate, DXChatBarMoreViewDelegate, DXMessageToolBarDelegate, LocationViewDelegate, EMCDDeviceManagerDelegate,EMCallManagerDelegate,MenuViewDelegate>
{
    UIMenuController *_menuController;
    UIMenuItem *_copyMenuItem;
    UIMenuItem *_deleteMenuItem;
    NSIndexPath *_longPressIndexPath;
    
    NSInteger _recordingCount;
    
    dispatch_queue_t _messageQueue;
    
    NSMutableArray *_messages;
    BOOL _isScrollToBottom;
    BOOL burnafterreadingLook;
    // UIView *coverView;
    NSInteger tableviewHight;
    // 右上角按钮
    UIButton *rightButton1;
    
    UIView *headViewLabel;
    BFPaperButton *weatherheadView;
    
    NSInteger m;
    NSInteger s;
    
    CGFloat _centerX;
    CGFloat _centerY;
    
//    NSInteger payCount;
}
//菜单
@property (nonatomic) BOOL isChatGroup;
@property (nonatomic) EMConversationType conversationType;
@property (strong, nonatomic) NSMutableArray *dataSource;//tableView数据源
@property (strong, nonatomic) SRRefreshView *slimeView;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) DXMessageToolBar *chatToolBar;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (strong, nonatomic) MessageReadManager *messageReadManager;//message阅读的管理者
@property (strong, nonatomic) EMConversation *conversation;//会话管理者
@property (strong, nonatomic) NSDate *chatTagDate;
@property (strong, nonatomic) NSMutableArray *messages;
@property (nonatomic) BOOL isScrollToBottom;
@property (nonatomic) BOOL isPlayingAudio;
@property (nonatomic) BOOL isKicked;
@property (strong, nonatomic) NSArray *PromptArr;
@property (strong, nonatomic) NSArray *truewordsArr;
@property NSInteger vibrationNumber;
@property (nonatomic, assign)BOOL isFriend;//是否是好友
//@property (nonatomic, assign)BOOL isSweetheart;//是否是情侣

@property (nonatomic, strong)MenuView *menuView;//菜单
@property (nonatomic, strong)UIView *bannedView;//被禁言遮挡视图

@property NSInteger type; //聊天状态
@property NSInteger status;//消息框输入状态

@property (nonatomic, strong)UIView *hintInterestTopic;//兴趣话题提示

//购买金币的view
//@property (nonatomic, strong)UIView *buyView;
//@property (nonatomic, strong)UILabel *buyLabel;
//@property (nonatomic, strong)NSArray *buyCostArr1;
//@property (nonatomic, strong)NSArray *buyCostArr2;
//@property NSInteger selectRow;

@property (nonatomic)BOOL isPresent;

//@property (nonatomic, strong)UIView *hintInterestTopic;//兴趣话题提示
@end

@implementation ChatViewController

- (instancetype)initWithChatter:(NSString *)chatter isGroup:(BOOL)isGroup
{
    EMConversationType type = isGroup ? eConversationTypeGroupChat : eConversationTypeChat;
    self = [self initWithChatter:chatter conversationType:type];
    if (self) {
    }
    
    return self;
}

- (instancetype)initWithChatter:(NSString *)chatter conversationType:(EMConversationType)type
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _isPlayingAudio = NO;
        _chatter = chatter;
        _conversationType = type;
        _messages = [NSMutableArray array];
        
        //根据接收者的username获取当前会话的管理者
        _conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:chatter
                                                                    conversationType:type];
        [_conversation markAllMessagesAsRead:YES];
    }
    
    return self;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.isPresent = YES;
    
}
- (BOOL)isChatGroup
{
    return _conversationType != eConversationTypeChat;
}

- (void)saveChatroom:(EMChatroom *)chatroom
{
    
    NSString *chatroomName = chatroom.chatroomSubject ? chatroom.chatroomSubject : @"";
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]];
    NSMutableDictionary *chatRooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
    if (chatroom.chatroomId && (![chatRooms objectForKey:chatroom.chatroomId]))
    {
        [chatRooms setObject:chatroomName forKey:chatroom.chatroomId];
        [ud setObject:chatRooms forKey:key];
        [ud synchronize];
    }
}

- (void)joinChatroom:(NSString *)chatroomId
{
    [self showHudInView:self.view hint:NSLocalizedString(@"chatroom.joining",@"Joining the chatroom")];
    __weak typeof(self) weakSelf = self;
    
    [[EaseMob sharedInstance].chatManager asyncJoinChatroom:chatroomId completion:^(EMChatroom *chatroom, EMError *error){
        if (weakSelf)
        {
            ChatViewController *strongSelf = weakSelf;
            [strongSelf hideHud];
            if (error && (error.errorCode != EMErrorChatroomJoined))
            {
                [strongSelf showHint:[NSString stringWithFormat:@"加入%@失败", chatroomId]];
            }
            else
            {
                [strongSelf saveChatroom:chatroom];
            }
        }
        else
        {
            if (!error || (error.errorCode == EMErrorChatroomJoined))
            {
                [[EaseMob sharedInstance].chatManager asyncLeaveChatroom:chatroomId completion:^(EMChatroom *chatroom, EMError *error){
                    [[EaseMob sharedInstance].chatManager removeConversationByChatter:chatroomId deleteMessages:YES append2Chat:YES];
                }];
            }
        }
    }];
}
- (void)setSweetheartApplyText:(NSString *)str chatUser:(MLUser *)chatUser
{
    MLSweetheartApply *sweetheartApply = [MLSweetheartApply object];
    sweetheartApply.remark = str;
    sweetheartApply.applier = [MLUser currentUser];
    sweetheartApply.user = chatUser;
    sweetheartApply.status = MLSweetheartApplyStatus_WAITING;
    [sweetheartApply saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            // 发送消息
            NSDictionary *params = @{@"touserId":chatUser.objectId, @"fromuserId":  [MLUser currentUser].objectId, @"nick":[MLUser currentUser].nickname,@"actions":ACTION_Pocketsweet_SWEET_APPLY};
            [AVCloud callFunctionInBackground:@"sendSweetApplyMsg" withParameters:params block:^(id object, NSError *error) {
                if (!error) {
                    [HUD Prompt:[NSString stringWithFormat:@"已向%@发起试恋请求",chatUser.nickname]];
                } else {
                    [HUD Prompt:@"网络错误,请重试"];
                }
            }];
        }else{
            [HUD Prompt:@"网络错误,请重试"];
        }
    }];
    
}
- (void)setFriendApplyText:(NSString *)str chatUser:(MLUser *)chatUser
{
    MLFriendApply *friendApply = [MLFriendApply object];
    friendApply.remark = str;
    friendApply.applier = [MLUser currentUser];
    friendApply.user = chatUser;
    friendApply.status = MLFriendApplyStatus_WAITING;
    [friendApply saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            // 发送消息
            NSDictionary *params = @{@"touserId":  chatUser.objectId, @"fromuserId":[MLUser currentUser].objectId,@"nick":[MLUser currentUser].nickname,@"actions":ACTION_FRIEND_APPLY};
            [AVCloud callFunctionInBackground:@"sendFriendApplyMsgShow" withParameters:params block:^(id object, NSError *error) {
                if (!error) {
                    [HUD Prompt:[NSString stringWithFormat:@"已向%@发起好友请求",chatUser.nickname]];
                } else {
                    [HUD Prompt:@"网络错误,请重试"];
                }
            }];
        }else{
            [HUD Prompt:@"网络错误,请重试"];
        }
    }];
    
}

- (void)screenEdgePanGR:(UIScreenEdgePanGestureRecognizer *)left
{
    //    CGPoint translation = [left translationInView:left.view];
    //
    //    NSLog(@"%f",translation.x);
    
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)clickLeftBt
{
    
    [self.navigationController popViewControllerAnimated:YES];
    [self.view removeFromSuperview];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    [self registerBecomeActive];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = RGBA(251, 251, 251, 1);
    
    
    
    //私密消息查看
    burnafterreadingLook = NO;
    //抖动
    self.PromptArr = @[@"你在干嘛啊?",@"怎么不理我 T T",@"戳你一下",@"hey~"];
    //真心话
    self.truewordsArr = @[@"你们家里谁的脾气最大",@"现在想被有钱人保养么",@"上厕所后洗手么",@"你希望你现在是多少岁",@"对窗外大喊：“我好寂寞阿。”",@"出去大喊“我的艾滋有救了。",@"你一共收藏了多少黄色小电影。",@"今天拉屎没有。",@"内衣/裤颜色",@"如果让你选择做一个电影中的角色，你会选谁呢？ "];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
#warning 以下三行代码必须写，注册为SDK的ChatManager的delegate
    [EMCDDeviceManager sharedInstance].delegate = self;
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    //注册为SDK的ChatManager的delegate
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [[EaseMob sharedInstance].callManager removeDelegate:self];
    // 注册为Call的Delegate
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllMessages:) name:@"RemoveAllMessages" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitGroup) name:@"ExitGroup" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertCallMessage:) name:@"insertCallMessage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name:@"applicationDidEnterBackground" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addHintMessage:) name:@"addHintMessage" object:nil];
    _messageQueue = dispatch_queue_create("easemob.com", NULL);
    _isScrollToBottom = YES;
    
    
    [self judgeUserType];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cmd:) name:@"cmd" object:nil];
    
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.slimeView];
    
    if([self.chatter isEqualToString:@"mlsystem"]){
        
    }else{
        [self.view addSubview:self.chatToolBar];
        
        //将self注册为chatToolBar的moreView的代理
        if ([self.chatToolBar.moreView isKindOfClass:[DXChatBarMoreView class]]) {
            [(DXChatBarMoreView *)self.chatToolBar.moreView setDelegate:self];
        }
    }
    
   
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyBoardHidden)];
    [self.tableView addGestureRecognizer:tap];
    //通过会话管理者获取已收发消息
    [self loadMoreMessages];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCallNotification:) name:@"callControllerClose" object:nil];
    
    if (_conversationType == eConversationTypeChatRoom)
    {
        [self joinChatroom:_chatter];
    }
    if([self.chatter isEqualToString:@"mlsystem"]){
       
        [self setTitle:@"无独团"];
        [_chatToolBar.stateButton setImage:[UIImage imageNamed:@"chat_phone-hui_icon"] forState:UIControlStateNormal];
        [_chatToolBar.stateButton setImage:[UIImage imageNamed:@"chat_phone-hui_icon"] forState:UIControlStateSelected];
        _chatToolBar.stateButton.enabled = NO;

    }else{
        self.menuView = [[MenuView alloc] initWithFrame:self.view.frame listArray:@[@"申请试恋",@"ta的资料",@"拉黑"]];
        self.menuView.delegate = self;
        [self.view addSubview:self.menuView];
    }
    
    //打电话
    [_chatToolBar.callPhoneBtn addTarget:self action:@selector(moreViewAudioCallAction:) forControlEvents:UIControlEventTouchUpInside];
    //聊天键盘
    [_chatToolBar.stateButton addTarget:self action:@selector(keyboardStateAction:) forControlEvents:UIControlEventTouchUpInside];
    //聊天键盘状态
    [_chatToolBar updateKeyboardState:NO];
    
    headViewLabel = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DeviceWidth, 80)];
    headViewLabel.backgroundColor = APPCOLOR(1);
    headViewLabel.alpha = 0;
    [self.view insertSubview:headViewLabel atIndex:[self.view.subviews count]-2];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(70, 10, DeviceWidth-80, 60)];
    label.text = @"申请和陌生人虚拟恋爱时,请保持社交礼仪。发送不良信息、骚扰和谩骂行为会降低你的等级。如被举报核实,账号将被封禁。";
    label.numberOfLines = 0;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:FontName size:13];
    [headViewLabel addSubview:label];
    
    UIImageView *icoimge =[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
    icoimge.image = [UIImage imageNamed:@"news_chat_tips_icon"];
    [icoimge setContentMode:UIViewContentModeScaleAspectFill];
    [headViewLabel addSubview:icoimge];
    
    if ([Utils isFriendObjectId:_chatUser.objectId]) {
        //是好友
        self.isFriend = YES;
    }else{
        [self interestTopicHint];
    }
}
- (void)interestTopicHint
{
    if(self.chatUser){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            if (self.isPresent) {
                _hintInterestTopic = [[UIView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, 80)];
                _hintInterestTopic.backgroundColor = APPCOLOR(1);
                _hintInterestTopic.alpha = 0;
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, DeviceWidth-20, 80)];
                label.numberOfLines = 0;
                label.textColor = [UIColor whiteColor];
                label.adjustsFontSizeToFitWidth = YES;
                label.font = kFont(14);
                label.text = [NSString stringWithFormat:@"试恋时请一定保持礼貌。发送不良信息、骚扰和谩骂如被对方截图举报，我们将及时核实，并按会员协议处理。"];
                [_hintInterestTopic addSubview:label];
                [[[UIApplication sharedApplication].delegate window] addSubview:_hintInterestTopic];
                [Utils Hidden:_hintInterestTopic Bool:YES];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if(_hintInterestTopic){
                        [Utils Hidden:_hintInterestTopic Bool:NO];
                        [_hintInterestTopic removeFromSuperview];
                    }
                    
                });
                
            }
            
        });
    }
}

- (void)judgeUserType
{
    
    if ([self.chatter isEqualToString:@"mlsystem"]) {
       
        tableviewHight = 40;
    }else if(self.isNullChatUser){
        AVQuery *query = [MLUser query];
        [query whereKey:@"objectId" equalTo:self.chatter];
        [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            
            if (error == nil) {
                MLUser *nUser = (MLUser *)object;
                self.chatUser = nUser;
                 [self chatUserTypeManage];
                [[ShareData shareData].chatterUsers setObject:nUser forKey:nUser.objectId];
                [Utils saveChatUserDataNicknameUser:nUser];
            }else{
                AVQuery *query = [MLUser query];
                [query whereKey:@"objectId" equalTo:self.chatter];
                [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                    
                    if (error == nil) {
                        MLUser *nUser = (MLUser *)object;
                        self.chatUser = nUser;
                         [self chatUserTypeManage];
                        [[ShareData shareData].chatterUsers setObject:nUser forKey:nUser.objectId];
                        [Utils saveChatUserDataNicknameUser:nUser];
                    }else{
                        [HUD Prompt:@"网络错误,返回重试"];
                    }
                    
                }];
            }
            
            
        }];
        
    }else{
        [self chatUserTypeManage];
    }
   
}
//根据用户类型进行处理
- (void)chatUserTypeManage
{
    if (self.chatUser) {
      
        self.isFriend = NO;
        
        if ([Utils isFriendObjectId:_chatUser.objectId]) {
            //是好友
            self.isFriend = YES;
        }else{
            //不是好友,需要查询好友关系确定不是好友
            self.isFriend = NO;
        }
        [self setupBarButtonItem];
        [self setButtonTitle];
        tableviewHight = self.chatToolBar.frame.size.height;
        //        [self weather];
        
        [Utils saveChatUserObjectID:self.chatUser.objectId];
        [Utils saveChatUserDataNicknameUser:self.chatUser];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.chatUser.reportCount>=6) {
                [HUD Prompt:@"该用户已被多人举报,聊天要谨慎哦"];
            }
        });
        
    }else{
        
        tableviewHight = 40;
    }
}

- (void)addHintMessage:(NSNotification *)notification
{
    NSDictionary *dic = [notification userInfo];
    NSString *objectId = [dic objectForKey:@"objectId"];
    if(self.chatUser){
        if ([objectId isEqualToString:self.chatUser.objectId]) {
            EMMessage *message = [dic objectForKey:@"message"];
            [self addMessage:message];
        }
        
    }else if([self.title isEqualToString:@"无独团"]){
        if ([objectId isEqualToString:@"mlsystem"]) {
            EMMessage *message = [dic objectForKey:@"message"];
            [self addMessage:message];
        }
    }
    
}


//投诉
- (void)clickComplaintView
{
    ReportUploadImageViewController *reportUIVC = [[ReportUploadImageViewController alloc] init];
    reportUIVC.reportee = self.chatUser;
    reportUIVC.isComplaint = YES;
    [Utils pushTabbarHidden:reportUIVC Selfvc:self];
}

//加好友,和创建订单 等回复才需要创建关系
- (void)addFriendAndSweetheart
{
    if(![Utils isFriendObjectId:self.chatUser.objectId]){
        //判断对方是否是好友
        // 加对方为好友
        [[MLUser currentUser] follow:self.chatUser.objectId andCallback:^(BOOL succeeded, NSError *error) {
            if (succeeded || error.code == kAVErrorDuplicateValue) {
                [self addShareDateFriendsUser:self.chatUser];
                NSDictionary *params = @{@"touserId": self.chatUser.objectId, @"fromuserId": [MLUser currentUser].objectId,@"nick":[MLUser currentUser].nickname,@"actions":ACTION_FRIEND_APPLY_ACCEPTED};
                [AVCloud callFunctionInBackground:@"sendFriendApplyMsg" withParameters:params block:^(id object, NSError *error) {
                    if (object) {
                        // NSLog(@"%@",object);
                    }
                }];
            }
        }];
    }
    
}


- (void)addShareDateFriendsUser:(MLUser *)user
{
    //添加为好友
    
    if ([ShareData shareData].friends&&[ShareData shareData].friends.count) {
        //判断是否已经是好友
        BOOL is = NO;
        for (MLUser *f in [ShareData shareData].friends) {
            if([f.objectId isEqualToString:user.objectId]){
                is = YES;
                break;
            }
        }
        
        if (!is) {
            [[ShareData shareData].friends addObject:user];
        }
    }
    self.isFriend = YES;
    [Utils savePassFriendObjectID:user.objectId];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMyFriendsData" object:self userInfo:nil];
    
}


- (NSInteger)manageDateBeginDate:(NSDate *)beginDate presentDate:(NSTimeInterval)presentInterval
{
    NSTimeInterval begin = [beginDate timeIntervalSince1970];
    NSTimeInterval cha = (presentInterval - begin);
    return cha;
}
//计算剩余时间
- (NSInteger)manageDateBeginDate:(NSDate *)beginDate presentDate:(NSTimeInterval)presentInterval buyMinute:(NSInteger )buyMinute
{
    NSTimeInterval begin = [beginDate timeIntervalSince1970];
    NSTimeInterval cha = (presentInterval - begin);
    NSTimeInterval buy = buyMinute * 60;
    return buy - cha;
}

#pragma -mark
- (void)handleCallNotification:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        //开始call
        self.isInvisible = YES;
    }
    else
    {
        //结束call
        self.isInvisible = NO;
    }
}

-(void)sendTextMsg:(NSDictionary *)notification
{
    //    NSDictionary *dic=[notification userInfo];
    [self sendTextMessageWithExt:[notification objectForKey:@"msg"] ext:[notification objectForKey:@"ext"]];
    //[ShareData shareData].callVC = nil;
}

- (void)keyboardStateAction:(UIButton*)button
{
    [AVAnalytics event:@"聊天页打电话"]; // 通知服务器一个点击事件。
    
    [self keyBoardHidden];
    if(button.selected){
       
        [_chatToolBar keyboardStateSwitch:YES btn:button];
    }else{
      [self callUp];
    }
    
}
- (void)lookUserData:(MLUser*)user

{
    if (user) {
        MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
        userInfoVC.userData = user;
        userInfoVC.popbool = YES;
        [self.navigationController pushViewController:userInfoVC animated:YES];
    }
    
}
//删除好友记录
- (void)deleteShareDateFriendsObjectId:(NSString *)objectId
{
    if ([ShareData shareData].friends) {
        
        //删除好友
        for (int i = 0; i<[ShareData shareData].friends.count; i++) {
            MLUser *n = [[ShareData shareData].friends objectAtIndex:i];
            if ([n.objectId isEqualToString:objectId]) {
                [[ShareData shareData].friends removeObjectAtIndex:i];
                break;
            }
        }
    }
    [Utils removeObjectForFriendObjectID:objectId];
    
}
-(void)cmd:(NSNotification *)notification
{
    if (self.chatUser) {
        NSDictionary *dic=[notification userInfo];
        EMMessage *message = [dic objectForKey:@"message"];
        if (message.from&&[message.from isEqualToString:@"new_friend"]) {
            NSArray *arr = message.messageBodies;
            if (arr) {
                EMCommandMessageBody *body= message.messageBodies.lastObject;
                if (body.action && [body.action isEqualToString:ACTION_FRIEND_APPLY_ACCEPTED]) {
                    NSDictionary *ext = message.ext;
                    if ([ext objectForKey:@"from"]&&self.chatUser.objectId &&[[ext objectForKey:@"from"] isEqualToString:self.chatUser.objectId ]) {
                        self.isFriend = YES;
                    }
                    
                }else if (body.action && [body.action isEqualToString:ACTION_FRIEND_DELETE]){
                    NSDictionary *ext = message.ext;
                    if ([ext objectForKey:@"from"]&&self.chatUser.objectId &&[[ext objectForKey:@"from"] isEqualToString:self.chatUser.objectId ]) {
                        // 删除好友
                        __weak ChatViewController *weakSelf = self;
                        [[MLUser currentUser] unfollow:[ext objectForKey:@"from"] andCallback:^(BOOL succeeded, NSError *error) {
                            if (succeeded) {
                                //weakSelf.isFriend = NO;
                                
                                [weakSelf.navigationController popViewControllerAnimated:YES];
                                // self.dropDownMenu.dropDownItems =  [self returnDropdownItems];
                                //[self.dropDownMenu reloadView];
                            }
                        }];
                    }
                }
                
            }
        }
        else if (message.from&&[message.from isEqualToString:@"new_chat_apply"]){
            //            NSArray *arr = message.messageBodies;
            //            if (arr) {
            //              //  EMCommandMessageBody *body= message.messageBodies.lastObject;
            ////                if (body.action && [body.action isEqualToString:ACTION_CHAT_APPLY_ACCEPT]){
            ////                    [self judgeIsDate];
            ////                }
            //            }
        }else if(message.from&&[message.from isEqualToString:self.chatUser.objectId]){
            
        }
        
    }
    
    
}
-(NSDictionary*)Weather:(NSString*)url
{
    NSURL *URL = [NSURL URLWithString: [[NSString stringWithFormat:@"%@",url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:URL];
    [request setHTTPMethod:@"POST"];
    NSHTTPURLResponse *urlResponse = nil;
    NSError *error = nil;
    NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:recervedData
                                                    options:NSJSONReadingAllowFragments
                                                      error:nil];
    return jsonObject;
}

//天气
-(void)weather{
    if (self.chatUser) {
        weatherheadView = [[BFPaperButton alloc]initWithFrame:CGRectMake(0, 0, DeviceWidth, HEADHIGH)];
        weatherheadView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.9];
        weatherheadView.loweredShadowOffset = CGSizeMake(1, 1);
        weatherheadView.loweredShadowOpacity = 0.3;
        weatherheadView.loweredShadowRadius = 0.7;
        [self.view insertSubview:weatherheadView atIndex:[self.view.subviews count]-2];
        __weak ChatViewController *weakSelf = self;
        [HttpPostExecutor postExecuteWithUrlStr:[[NSString stringWithFormat:@"http://apistore.baidu.com/microservice/weather?cityname=%@",self.chatUser.location_city] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                                      Paramters:nil
                            FinishCallbackBlock:^(NSString *result){
                                // 执行post请求完成后的逻辑
                                if (result) {
                                    NSData* data = [result dataUsingEncoding:NSASCIIStringEncoding];
                                    if(data){
                                        NSDictionary *chatWeatherDict = [NSJSONSerialization JSONObjectWithData:data
                                                                                                        options:NSJSONReadingAllowFragments
                                                                                                          error:nil];
                                        
                                        if ([[chatWeatherDict objectForKey:@"retData"] count] != 0) {
                                            UIImageView *chatAvatarImg = [[UIImageView alloc]init];
                                            chatAvatarImg.frame = CGRectMake(5, (HEADHIGH-40)/2, 40, 40);
                                            chatAvatarImg.layer.masksToBounds = YES;//开启圆角
                                            [chatAvatarImg.layer setCornerRadius:20];
                                            [chatAvatarImg setContentMode:UIViewContentModeScaleAspectFill];
                                            if (!weakSelf.chatUser.subAvatar || [weakSelf.chatUser.subAvatar isEqualToString:@""]) {
                                                [chatAvatarImg sd_setImageWithURL:[NSURL URLWithString:weakSelf.chatUser.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
                                                
                                            }else{
                                                [chatAvatarImg sd_setImageWithURL:[NSURL URLWithString:weakSelf.chatUser.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
                                            }
                                            // [chatAvatarImg sd_setImageWithURL:[NSURL URLWithString:weakSelf.chatUser.avatar.url]];
                                            [weatherheadView addSubview:chatAvatarImg];
                                            
                                            
                                            UILabel *chatName = [[UILabel alloc]initWithFrame:CGRectMake(50,0, (DeviceWidth/2)-50, 17)];
                                            chatName.text = weakSelf.chatUser.nickname;
                                            chatName.font = [UIFont fontWithName:FontName size:12];
                                            chatName.textAlignment = NSTextAlignmentLeft;
                                            [weatherheadView addSubview:chatName];
                                            
                                            UILabel *chatCitylabel = [[UILabel alloc]initWithFrame:CGRectMake(50, (HEADHIGH-12)/2, (DeviceWidth/2)-50, 12)];
                                            chatCitylabel.text = [[chatWeatherDict objectForKey:@"retData"] objectForKey:@"city"];
                                            chatCitylabel.font = [UIFont fontWithName:FontName size:12];
                                            chatCitylabel.textAlignment = NSTextAlignmentLeft;
                                            [weatherheadView addSubview:chatCitylabel];
                                            
                                            
                                            UILabel *chatWeatherlabel = [[UILabel alloc]initWithFrame:CGRectMake(50, HEADHIGH-17, (DeviceWidth/2)-50, 12)];
                                            chatWeatherlabel.text = [NSString stringWithFormat:@"%@ %@°",[[chatWeatherDict objectForKey:@"retData"] objectForKey:@"weather"],[[chatWeatherDict objectForKey:@"retData"] objectForKey:@"temp"]];
                                            chatWeatherlabel.font = [UIFont fontWithName:FontName size:12];
                                            chatWeatherlabel.textAlignment = NSTextAlignmentLeft;
                                            [weatherheadView addSubview:chatWeatherlabel];
                                            
                                        }
                                    }
                                    
                                    
                                }
                            }];
        
        
        
        [HttpPostExecutor postExecuteWithUrlStr:[[NSString stringWithFormat:@"http://apistore.baidu.com/microservice/weather?cityname=%@",[MLUser currentUser].location_city] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                                      Paramters:nil
                            FinishCallbackBlock:^(NSString *result){
                                // 执行post请求完成后的逻辑
                                
                                if (result) {
                                    NSData* data = [result dataUsingEncoding:NSASCIIStringEncoding];
                                    if (data) {
                                        NSDictionary *meWeatherDict = [NSJSONSerialization JSONObjectWithData:data
                                                                                                      options:NSJSONReadingAllowFragments
                                                                                                        error:nil];
                                        if ([[meWeatherDict objectForKey:@"retData"] count] != 0) {
                                            
                                            MLUser *currentUser = [MLUser currentUser];
                                            UIImageView *userAvatarImg = [[UIImageView alloc]init];
                                            userAvatarImg.frame = CGRectMake(DeviceWidth-45, (HEADHIGH-40)/2, 40, 40);
                                            userAvatarImg.layer.masksToBounds = YES;//开启圆角
                                            [userAvatarImg.layer setCornerRadius:20];
                                            [userAvatarImg setContentMode:UIViewContentModeScaleAspectFill];
                                            
                                            if (!currentUser.subAvatar || [currentUser.subAvatar isEqualToString:@""]) {
                                                [userAvatarImg sd_setImageWithURL:[NSURL URLWithString:currentUser.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
                                                
                                            }else{
                                                [userAvatarImg sd_setImageWithURL:[NSURL URLWithString:currentUser.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
                                            }
                                            
                                            // [userAvatarImg sd_setImageWithURL:[NSURL URLWithString:currentUser.avatar.url]];
                                            [weatherheadView addSubview:userAvatarImg];
                                            
                                            
                                            UILabel *meName = [[UILabel alloc]initWithFrame:CGRectMake(DeviceWidth-((DeviceWidth/2)-50)-50, 0, (DeviceWidth/2)-50, 17)];
                                            meName.text = currentUser.nickname;
                                            meName.font = [UIFont fontWithName:FontName size:12];
                                            meName.textAlignment = NSTextAlignmentRight;
                                            [weatherheadView addSubview:meName];
                                            
                                            UILabel *meCitylabel = [[UILabel alloc]initWithFrame:CGRectMake(DeviceWidth-((DeviceWidth/2)-50)-50, (HEADHIGH-12)/2, (DeviceWidth/2)-50, 12)];
                                            meCitylabel.text = [[meWeatherDict objectForKey:@"retData"] objectForKey:@"city"];
                                            meCitylabel.font = [UIFont fontWithName:FontName size:12];
                                            meCitylabel.textAlignment = NSTextAlignmentRight;
                                            [weatherheadView addSubview:meCitylabel];
                                            
                                            
                                            UILabel *meWeatherlabel = [[UILabel alloc]initWithFrame:CGRectMake(DeviceWidth-((DeviceWidth/2)-50)-50, HEADHIGH-17, (DeviceWidth/2)-50, 12)];
                                            meWeatherlabel.text = [NSString stringWithFormat:@"%@° %@",[[meWeatherDict objectForKey:@"retData"] objectForKey:@"temp"],[[meWeatherDict objectForKey:@"retData"] objectForKey:@"weather"]];
                                            meWeatherlabel.font = [UIFont fontWithName:FontName size:12];
                                            meWeatherlabel.textAlignment = NSTextAlignmentRight;
                                            [weatherheadView addSubview:meWeatherlabel];
                                        }
                                    }
                                    
                                }
                            }];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [Utils Hidden:weatherheadView Bool:NO];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weatherheadView removeFromSuperview];
            });
        });
        
        //副标题
        // self.subtitle = [NSString stringWithFormat:@"我们在一起%@天",@"132"];
    }
    
}


- (void)setupBarButtonItem
{
    if (self.chatUser) {
        UIButton *leftBt = [UIButton buttonWithType:UIButtonTypeCustom];
        [leftBt sizeToFit];
        [leftBt setTitle:@"返回" forState:UIControlStateNormal];
        [leftBt setContentMode:UIViewContentModeCenter];
        [leftBt setImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
        [leftBt setImageEdgeInsets:UIEdgeInsetsMake(-2,-18, -2, 0)];
        [leftBt setTitleEdgeInsets:UIEdgeInsetsMake(0, -12, 0, -10)];
        leftBt.titleLabel.font = kFont(17);
        leftBt.frame = CGRectMake(0, 0, 40, 30);
        leftBt.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [leftBt addTarget:self action:@selector(clickLeftBt) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBarBt = [[UIBarButtonItem alloc] initWithCustomView:leftBt];
        self.navigationItem.leftBarButtonItems = @[leftBarBt];
        // 右上角按钮
        rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton1.frame = CGRectMake(0, 0, 30, 30);
       // [rightButton1 sizeToFit];
        rightButton1.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [rightButton1 setImage:[UIImage imageNamed:@"love_normal_icon"] forState:UIControlStateNormal];
        [rightButton1 addTarget:self action:@selector(clickRightButton) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarButton1  = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
        
        
        self.navigationItem.rightBarButtonItems = @[rightBarButton1];
        
        _centerX = self.view.bounds.size.width / 2;
        _centerY = self.view.bounds.size.height / 2;
        
        //屏幕边缘手势
        UIScreenEdgePanGestureRecognizer *screenEdgePanGR = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(screenEdgePanGR:)];
        screenEdgePanGR.edges  = UIRectEdgeLeft;
        [self.view addGestureRecognizer:screenEdgePanGR];
        //UIBarButtonItem 加上返回按钮之后不可以手势返回，是因为当前的手势代理不为空，需要把当前的手势代理值为nil
        // self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}
- (void)clickRightButton
{
    
    [self toggleView];
   
}
- (void)setButtonTitle
{
    if (self.isFriend) {
        [self.menuView setListTitleArr:@[@"申请试恋",@"ta的资料",@"拉黑"]];
    }else{
        [self.menuView setListTitleArr:@[@"申请试恋",@"拉黑"]];
    }
    
    if([Utils isSweetheartObjectId:_chatUser.objectId]){
        [self.menuView setListTitleArr:@[@"ta的资料",@"拉黑"]];
    }
    
}
-(void)toggleView
{
    if([ShareData shareData].sweetheartType == sweetheartType_NO){
        //没有查询过恋人关系,开始查询
        [HUD Prompt:@"正在查询试恋关系"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartChange" object:self userInfo:nil];
        return;
    }else if([ShareData shareData].sweetheartType == sweetheartType_QUERY){
        [HUD Prompt:@"正在查询试恋关系"];
        return;
    }else{
        
    }
    [self setButtonTitle];
    
    
    
    if (self.menuView.alpha == 0) {
        [Utils Hidden:self.menuView Bool:YES];
    }else{
        [Utils Hidden:self.menuView Bool:NO];
    }
}
- (void)clickListButton:(UIButton *)bt
{
    [self keyBoardHidden];
    [Utils Hidden:self.menuView Bool:NO];
    if (_chatUser == nil) {
        return;
    }
    if ([bt.titleLabel.text isEqualToString:@"拉黑"]){
        HUD*hud = [[HUD alloc]init];
        [hud HUDImage:nil Title:@"加入黑名单" Content:@"你确定要拉黑他吗?" CANCEL:@"取消" Confirm:@"确定"];
        hud.Confirm  = ^{
            //确定加黑名单
            EMError *error = [[EaseMob sharedInstance].chatManager blockBuddy:self.chatUser.objectId relationship:eRelationshipBoth];
            if (!error) {
                [HUD Prompt:@"成功加入黑名单"];
                //删除回话
                [[EaseMob sharedInstance].chatManager removeConversationByChatter:self.chatUser.objectId deleteMessages:YES append2Chat:YES];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                NSString *str = [NSString stringWithFormat:@"%@",error];
                if ([str isEqualToString:@"already exist in black list."]) {
                    [HUD Prompt:@"ta已经在黑名单中了"];
                }else{
                    [HUD Prompt:str ];
                }
            }
        };
        
        hud.Cancel = ^{
            NSLog(@"取消");
        };
        [self.view addSubview:hud];
    }else if ([bt.titleLabel.text isEqualToString:@"解除好友"]){
        __block HUD*hud = [[HUD alloc]init];
        [hud HUDTitle:@"解除好友" TextStr:@"请输入理由" CANCEL:@"取消" Confirm:@"确定"];
        hud.Confirm  = ^{
            UITextField *tf = hud.textField;
            //删除好友
            [AVAnalytics event:@"解除好友"]; // 通知服务器一个点击事件。
            __weak ChatViewController *weakSelf = self;
            [[MLUser currentUser] unfollow:self.chatUser.objectId andCallback:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    MLUser *user = [MLUser currentUser];
                    NSArray *users = [NSArray arrayWithObjects:user,weakSelf.chatUser, nil];
                    AVQuery *queryFollowee = [AVQuery queryWithClassName:@"_Followee"];
                    [queryFollowee whereKey:@"user" containedIn:users];
                    [queryFollowee whereKey:@"followee" containedIn:users];
                    [queryFollowee deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        //取消关注
                    }];
                    AVQuery *queryFollower = [AVQuery queryWithClassName:@"_Follower"];
                    [queryFollower whereKey:@"user" containedIn:users];
                    [queryFollower whereKey:@"follower" containedIn:users];
                    [queryFollower deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        //取消关注
                    }];
                    
                    //删除好友
                    for (int i = 0; i<[ShareData shareData].friends.count; i++) {
                        MLUser *n = [[ShareData shareData].friends objectAtIndex:i];
                        if ([n.objectId isEqualToString:weakSelf.chatUser.objectId]) {
                            [[ShareData shareData].friends removeObjectAtIndex:i];
                            break;
                        }
                    }
                    AVQuery *date1 = [MLDate query];
                    AVQuery *date2 = [MLDate query];
                    [date1 whereKey:@"user"  equalTo:weakSelf.chatUser];
                    [date1 whereKey:@"sponsor"  equalTo:[MLUser currentUser]];
                    [date2 whereKey:@"user"  equalTo:[MLUser currentUser]];
                    [date2 whereKey:@"sponsor"  equalTo:weakSelf.chatUser];
                    AVQuery *date = [AVQuery orQueryWithSubqueries:[NSArray arrayWithObjects:date1,date2, nil]];
                    [date deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        // 删除通话申请
                        
                    }];
                    
                    //删除回话
                    [[EaseMob sharedInstance].chatManager removeConversationByChatter:weakSelf.chatUser.objectId deleteMessages:YES append2Chat:YES];
                    [self.navigationController popViewControllerAnimated:YES];
                    
                    NSDictionary *params = @{@"touserId": weakSelf.chatUser.objectId, @"fromuserId": [MLUser currentUser].objectId,@"nick":[MLUser currentUser].nickname,@"actions":ACTION_FRIEND_DELETE};
                    [AVCloud callFunctionInBackground:@"sendFriendApplyMsg" withParameters:params block:^(id object, NSError *error) {
                        if (!error) {
                            NSDictionary *paramsF = @{@"touserId": weakSelf.chatUser.objectId,@"msg":[NSString stringWithFormat:@"%@和你解除好友关系%@",[MLUser currentUser].nickname,tf.text.length != 0?  [NSString stringWithFormat:@",原因:%@",tf.text]:@""]};
                            [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:paramsF block:^(id object, NSError *error) {
                                if (error) {
                                    NSLog(@"解除好友关系错误");
                                }
                            }];
                            [HUD Prompt:[NSString stringWithFormat:@"已和%@解除好友关系成功",self.chatUser.nickname]];
                            
                            weakSelf.isFriend = NO;
                            rightButton1.hidden = weakSelf.isFriend;
                            
                            [weakSelf deleteShareDateFriendsObjectId:weakSelf.chatUser.objectId];
                        } else {
                            [HUD Prompt:@"网络错误，返回重试"];
                        }
                    }];
                }
            }];
            
        };
        hud.Cancel = ^{
            NSLog(@"取消");
        };
        [self.view addSubview:hud];
        
        
    }else if([bt.titleLabel.text isEqualToString:@"加为好友"]){
        HUD*hud = [[HUD alloc]init];
        [hud HUDTitle:@"申请成为对方的好友" TextStr:@"您向对方申请试恋的理由" CANCEL:@"取消" Confirm:@"确定"];
        __weak ChatViewController *weakSelf = self;
        hud.Confirm  = ^{
            [AVAnalytics event:@"加为好友"]; // 通知服务器一个点击事件。
            UITextField *tf = hud.textField;
            if (tf&&tf.text.length<=50) {
                // 发送加好友申请
                //先判断有没有申请过
                AVQuery *q1 = [MLFriendApply query];
                [q1 whereKey:@"user"  equalTo:weakSelf.chatUser];
                [q1 whereKey:@"applier"  equalTo:[MLUser currentUser]];
                
                [q1 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    //先查询是否有记录,有的话就不让申请
                    
                    if (error||objects.count==0) {
                        //无记录
                        [weakSelf setFriendApplyText:tf.text chatUser:weakSelf.chatUser];
                    }else{
                        for (int i = 0; i<objects.count; i++) {
                            MLFriendApply *d = [objects objectAtIndex:i];
                            if (i == 0) {
                                if(d.status == MLFriendApplyStatus_WAITING){
                                    //  [HUD Prompt:@"你已经申请过了,请不要重复申请"];
                                }else {
                                    [d deleteInBackground];
                                    [weakSelf setFriendApplyText:tf.text chatUser:weakSelf.chatUser];
                                }
                            }else{
                                [d deleteInBackground];
                            }
                        }
                        
                    }
                    
                }];
            }else{
                [HUD Prompt:@"字数不能大于50个字"];
            }
            
        };
        hud.Cancel = ^{
            NSLog(@"取消");
        };
        [self.view addSubview:hud];
    }else if([bt.titleLabel.text isEqualToString:@"申请试恋"]){
        
        if([ShareData shareData].sweetheartType == sweetheartType_NO){
            //没有查询过恋人关系,开始查询
            [HUD Prompt:@"正在查询试恋关系"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartChange" object:self userInfo:nil];
            return;
        }else if([ShareData shareData].sweetheartType == sweetheartType_QUERY){
            [HUD Prompt:@"正在查询试恋关系"];
            return;
        }else{
            
        }
        //对方不是我的恋人
        NSInteger number = 0;
        if ([ShareData shareData].firstView.sweetheart) {
            number++;
        }
        if ([ShareData shareData].secondView.sweetheart) {
            number++;
        }
        if ([ShareData shareData].thirdView.sweetheart) {
            number++;
        }
        if (number>=3) {
            [HUD Prompt:@"专心珍惜现在的恋人吧"];
            return;
        }
        
        
        
        
        HUD*hud = [[HUD alloc]init];
        [hud HUDTitle:@"申请与对方试恋" TextStr:@"您向对方申请试恋的理由" CANCEL:@"取消" Confirm:@"确定"];
        __weak ChatViewController *weakSelf = self;
        hud.Confirm  = ^{
            [AVAnalytics event:@"加为试恋申请"]; // 通知服务器一个点击事件。
           __block UITextField *tf = hud.textField;
            if (tf&&tf.text.length<=50) {
                // 发送加好友申请
                //先判断有没有申请过
                AVQuery *q1 = [MLSweetheartApply query];
                [q1 whereKey:@"user"  equalTo:weakSelf.chatUser];
                [q1 whereKey:@"applier"  equalTo:[MLUser currentUser]];
                [q1 whereKey:@"status"  equalTo:[NSNumber numberWithInteger:MLSweetheartApplyStatus_WAITING]];
                [q1 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    //先查询是否有记录,有的话就不让申请
                    
                    if (error||objects.count==0) {
                        //无记录
                        [weakSelf setSweetheartApplyText:tf.text chatUser:weakSelf.chatUser];
                    }else{
                        for (int i = 0; i<objects.count; i++) {
                            MLSweetheartApply *d = [objects objectAtIndex:i];
                            if (i == 0) {
                                if(d.status == MLSweetheartApplyStatus_WAITING){
                                    //  [HUD Prompt:@"你已经申请过了,请不要重复申请"];
                                }else {
                                    [d deleteInBackground];
                                    [weakSelf setSweetheartApplyText:tf.text chatUser:weakSelf.chatUser];
                                }
                            }else{
                                [d deleteInBackground];
                            }
                        }
                        
                    }
                    
                }];
            }else{
                [HUD Prompt:@"字数不能大于50个字"];
            }
            
        };
        hud.Cancel = ^{
            NSLog(@"取消");
        };
        [self.view addSubview:hud];
    }else if([bt.titleLabel.text isEqualToString:@"ta的资料"]){
        [self lookUserData:self.chatUser];
    }else if([bt.titleLabel.text isEqualToString:@"我要分手"]){
        
        __block HUD*hud = [[HUD alloc]init];
        [hud HUDTitle:@"我要分手" TextStr:@"请输入理由" CANCEL:@"取消" Confirm:@"确定"];
        hud.Confirm  = ^{
            UITextField *tf = hud.textField;
            
            [AVAnalytics event:@"我要分手"]; // 通知服务器一个点击事件。
            __weak ChatViewController *weakSelf = self;
            MLUser *user = [MLUser currentUser];
            ShareData *sharedata = [ShareData shareData];
            if (sharedata.firstView.sweetheart) {
                if (([sharedata.firstView.sweetheart.sponsor.objectId isEqualToString:self.chatUser.objectId]&&[sharedata.firstView.sweetheart.winner.objectId isEqualToString:user.objectId])||([sharedata.firstView.sweetheart.winner.objectId isEqualToString:self.chatUser.objectId]&&[sharedata.firstView.sweetheart.sponsor.objectId isEqualToString:user.objectId])) {
                    //分手
                    [self separateSweetheartView:sharedata.firstView separateStr:tf.text];
                }
            }
            if (sharedata.secondView.sweetheart) {
                if (([sharedata.secondView.sweetheart.sponsor.objectId isEqualToString:self.chatUser.objectId]&&[sharedata.secondView.sweetheart.winner.objectId isEqualToString:user.objectId])||([sharedata.secondView.sweetheart.winner.objectId isEqualToString:self.chatUser.objectId]&&[sharedata.secondView.sweetheart.sponsor.objectId isEqualToString:user.objectId])) {
                    //分手
                    [self separateSweetheartView:sharedata.secondView separateStr:tf.text];
                }
                
            }
            if (sharedata.thirdView.sweetheart) {
                if (([sharedata.secondView.sweetheart.sponsor.objectId isEqualToString:self.chatUser.objectId]&&[sharedata.secondView.sweetheart.winner.objectId isEqualToString:user.objectId])||([sharedata.secondView.sweetheart.winner.objectId isEqualToString:self.chatUser.objectId]&&[sharedata.secondView.sweetheart.sponsor.objectId isEqualToString:user.objectId])) {
                    //分手
                    [self separateSweetheartView:sharedata.thirdView separateStr:tf.text];
                }
                
            }
        };
        hud.Cancel = ^{
            NSLog(@"取消");
        };
        [self.view addSubview:hud];
    }else if([bt.titleLabel.text isEqualToString:@"申请试恋"]){
        
    }
}
- (void)separateSweetheartView:(SweetheartView *)sweetheartView separateStr:(NSString *)str
{
    __weak ChatViewController *weakSelf = self;
    [AVCloud callFunctionInBackground:@"getNetTime" withParameters:nil block:^(id objectt, NSError *errorr) {
        
        if (!errorr) {
            NSString *time = objectt;
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:[time longLongValue]/1000];
            sweetheartView.sweetheart.brokeUpDate = date;
            NSInteger count = [weakSelf manageDateBeginDate:sweetheartView.sweetheart.togetherDate presentDate:[time longLongValue]/1000];
            sweetheartView.sweetheart.togetherBefore += count/60;
            sweetheartView.sweetheart.status = 0;
            [sweetheartView.sweetheart saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    //分手成功
                    [sweetheartView separateIsCommon:YES separateStr:str];
                }else{
                    [HUD Prompt:@"分手失败"];
                }
            }];
        }else{
            [HUD Prompt:@"分手失败"];
        }
        
    }];
    
    
    //
    
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"isShowPicker"];
    if (_isScrollToBottom) {
        [self scrollViewToBottom:NO];
    }
    else{
        _isScrollToBottom = YES;
    }
    //检查是否被禁言
    [self inspectionBanned];
}
- (UIView *)bannedView
{
    if (_bannedView==nil) {
        _bannedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, [DXMessageToolBar defaultHeight])];
        UILabel *label =[[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, [DXMessageToolBar defaultHeight])];
        label.text = @"您已经被禁言24小时";
        label.textColor = RGBA(138, 138, 138, 1);
        label.textAlignment = NSTextAlignmentCenter;
        [_bannedView addSubview:label];
        _bannedView.backgroundColor = [UIColor whiteColor];
        [_chatToolBar addSubview:_bannedView];
    }
    return _bannedView;
};
- (void)inspectionBanned
{
    MLUser *user = [MLUser currentUser];
    if (user.status == MLUserStatus_BANYAN) {
        //判断禁言时间
        //获取当前时间
        NSDate *adate = [NSDate date];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate: adate];
        NSDate *localeDate = [adate  dateByAddingTimeInterval: interval];
        double intervalTime =  [localeDate timeIntervalSinceReferenceDate] - [user.forbiddenTime timeIntervalSinceReferenceDate];
        //   long lTime = labs((long)intervalTime);
        NSInteger hour = intervalTime / 3600;
        if (hour<24) {
            //被禁言
            self.bannedView.hidden = NO;
        }else{
            //禁言时间到了,修改用户资料
            user.status = MLUserStatus_NORMAL;
            [user saveInBackground];
            self.bannedView.hidden = YES;
        }
    }else{
        self.bannedView.hidden = YES;
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.isPresent = NO;
   
    if(_hintInterestTopic){
        _hintInterestTopic.alpha = 0;
        [_hintInterestTopic removeFromSuperview];
    }
    
    // 设置当前conversation的所有message为已读
    [_conversation markAllMessagesAsRead:YES];
    [[EMCDDeviceManager sharedInstance] disableProximitySensor];
    self.isInvisible = YES;
   
    
}

- (void)dealloc
{
   
    _delelgate = nil;
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    _tableView = nil;
    
    _slimeView.delegate = nil;
    _slimeView = nil;
    
    _chatToolBar.delegate = nil;
    _chatToolBar = nil;
    [[EMCDDeviceManager sharedInstance] stopPlaying];
    [EMCDDeviceManager sharedInstance].delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
#warning 以下第一行代码必须写，将self从ChatManager的代理中移除
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [[EaseMob sharedInstance].callManager removeDelegate:self];
    if (_conversation.conversationType == eConversationTypeChatRoom && !_isKicked)
    {
        //退出聊天室，删除会话
        NSString *chatter = [_chatter copy];
        [[EaseMob sharedInstance].chatManager asyncLeaveChatroom:chatter completion:^(EMChatroom *chatroom, EMError *error){
            [[EaseMob sharedInstance].chatManager removeConversationByChatter:chatter deleteMessages:YES append2Chat:YES];
        }];
    }
}
- (void)back
{
    //判断当前会话是否为空，若符合则删除该会话
    EMMessage *message = [_conversation latestMessage];
    if (message == nil) {
        [[EaseMob sharedInstance].chatManager removeConversationByChatter:_conversation.chatter deleteMessages:NO append2Chat:YES];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setIsInvisible:(BOOL)isInvisible
{
    _isInvisible =isInvisible;
    if (!_isInvisible)
    {
        NSMutableArray *unreadMessages = [NSMutableArray array];
        for (EMMessage *message in self.messages)
        {
            if ([self shouldAckMessage:message read:NO])
            {
                [unreadMessages addObject:message];
            }
        }
        if ([unreadMessages count])
        {
            [self sendHasReadResponseForMessages:unreadMessages];
        }
        
        [_conversation markAllMessagesAsRead:YES];
    }
}

#pragma mark - helper
- (NSURL *)convert2Mp4:(NSURL *)movUrl {
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                              presetName:AVAssetExportPresetHighestQuality];
        mp4Url = [movUrl copy];
        mp4Url = [mp4Url URLByDeletingPathExtension];
        mp4Url = [mp4Url URLByAppendingPathExtension:@"mp4"];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSLog(@"failed， error:%@.", exportSession.error);
                } break;
                case AVAssetExportSessionStatusCancelled: {
                    NSLog(@"cancelled.");
                } break;
                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"completed.");
                } break;
                default: {
                    NSLog(@"others.");
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        if (wait) {
            //dispatch_release(wait);
            wait = nil;
        }
    }
    
    return mp4Url;
}


#pragma mark - getter

- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
}

- (SRRefreshView *)slimeView
{
    if (_slimeView == nil) {
        _slimeView = [[SRRefreshView alloc] init];
        _slimeView.delegate = self;
        _slimeView.upInset = 0;
        _slimeView.slimeMissWhenGoingBack = YES;
        _slimeView.slime.bodyColor = APPCOLOR(1);
        _slimeView.slime.skinColor = [UIColor whiteColor];
        _slimeView.slime.lineWith = 1;
        _slimeView.slime.shadowBlur = 0;
        _slimeView.slime.shadowColor = [UIColor redColor];
    }
    
    return _slimeView;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - tableviewHight) style:UITableViewStylePlain];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = RGBA(251, 251, 251, 1);
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 10, 0);//偏移量
        
        UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
        lpgr.minimumPressDuration = .5;
        [_tableView addGestureRecognizer:lpgr];
    }
    
    return _tableView;
}

- (DXMessageToolBar *)chatToolBar
{
    if (_chatToolBar == nil) {
        _chatToolBar = [[DXMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - [DXMessageToolBar defaultHeight], self.view.frame.size.width, [DXMessageToolBar defaultHeight])];
        _chatToolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _chatToolBar.delegate = self;
        
        ChatMoreType type = self.isChatGroup == YES ? ChatMoreTypeGroupChat : ChatMoreTypeChat;
        _chatToolBar.moreView = [[DXChatBarMoreView alloc] initWithFrame:CGRectMake(0, (kVerticalPadding * 2 + kInputTextViewMinHeight), _chatToolBar.frame.size.width, 80) typw:type];
        _chatToolBar.moreView.backgroundColor = [UIColor lightGrayColor];
        _chatToolBar.moreView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    }
    
    return _chatToolBar;
}

- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.modalPresentationStyle= UIModalPresentationOverFullScreen;
        _imagePicker.delegate = self;
    }
    
    return _imagePicker;
}

- (MessageReadManager *)messageReadManager
{
    if (_messageReadManager == nil) {
        _messageReadManager = [MessageReadManager defaultManager];
    }
    
    return _messageReadManager;
}

- (NSDate *)chatTagDate
{
    if (_chatTagDate == nil) {
        _chatTagDate = [NSDate dateWithTimeIntervalInMilliSecondSince1970:0];
    }
    
    return _chatTagDate;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row < [self.dataSource count]) {
        id obj = [self.dataSource objectAtIndex:indexPath.row];
        if ([obj isKindOfClass:[NSString class]]) {
            EMChatTimeCell *timeCell = (EMChatTimeCell *)[tableView dequeueReusableCellWithIdentifier:@"MessageCellTime"];
            if (timeCell == nil) {
                timeCell = [[EMChatTimeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MessageCellTime"];
                timeCell.backgroundColor = [UIColor clearColor];
                timeCell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            timeCell.textLabel.text = (NSString *)obj;
            
            return timeCell;
        }
        else{
            MessageModel *model = (MessageModel *)obj;
            // 普通消息
            //未读的震动
            if (!model.message.isRead) {
                if ([[model.message.ext objectForKey:@"notification"]isEqualToString:EMMESSAGE_EXT_TYPE_JITTER_APPLY]){
                    [HUD shakeAnimationForView:self.view.window];
                    model.message.isRead = YES;
                    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                }
            }
            
            // 小灰条消息的cell
            NSDictionary *ext = model.message.ext;
            if (ext && [[ext objectForKey:@"type"] isEqual: @EMMESSAGE_EXT_TYPE_CHAT_NOTIFICATION_MSG]) {
                EMChatNotiCell *notiCell = (EMChatNotiCell *)[tableView dequeueReusableCellWithIdentifier:@"MessageCellNoti"];
                if (notiCell == nil) {
                    notiCell = [[EMChatNotiCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MessageCellNoti"];
                    notiCell.selectionStyle = UITableViewCellSelectionStyleNone;
                }
                
                notiCell.textLabel.text = model.content;
                return notiCell;
            }else if (ext && [[ext objectForKey:@"giftType"] isEqual: @EMMESSAGE_EXT_TYPE_GIFT_MSG]){
                // NSString *gift = @"chatGiftCell";
                
                // ChatGiftTableViewCell *giftCell = (ChatGiftTableViewCell *)[tableView dequeueReusableCellWithIdentifier:gift];
                ChatGiftTableViewCell *giftCell = [[ChatGiftTableViewCell alloc] initWithMessageModel:model reuseIdentifier:nil];
                if (giftCell == nil) {
                    //  giftCell = [[ChatGiftTableViewCell alloc] initWithMessageModel:model reuseIdentifier:gift];
                    
                }
                giftCell.backgroundColor = [UIColor clearColor];
                giftCell.selectionStyle = UITableViewCellSelectionStyleNone;
                if (model.isSender) {
                    MLUser *currentUser = [MLUser currentUser];
                    model.nickName = currentUser.nickname;
                    
                    
                    if (!currentUser.subAvatar || [currentUser.subAvatar isEqualToString:@""]) {
                        model.headImageURL = [NSURL URLWithString:currentUser.avatar.url];
                    }else{
                        model.headImageURL = [NSURL URLWithString:currentUser.subAvatar];
                    }
                    
                    
                    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapUserHeadImage)];
                    [giftCell.headImageView addGestureRecognizer:tap];
                } else {
                    if (self.chatUser) {
                        model.nickName = self.chatUser.nickname;
                        if (self.chatUser.avatar.url||self.chatUser.subAvatar){
                            if (!self.chatUser.subAvatar || [self.chatUser.subAvatar isEqualToString:@""]) {
                                model.headImageURL = [NSURL URLWithString:self.chatUser.avatar.url];
                            }else{
                                model.headImageURL = [NSURL URLWithString:self.chatUser.subAvatar];
                            }
                        }
                    }else{
                        NSDictionary *userDic = [Utils getUserNicknameHeadurlObjectId:self.chatter];
                        NSString *nickname = [userDic objectForKey:@"nickname"];
                        NSString *headurl = [userDic objectForKey:@"headurl"];
                        model.nickName = nickname;
                        model.headImageURL = [NSURL URLWithString:headurl];
                    }
                    
                    
                    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapChatHeadImage)];
                    [giftCell.headImageView addGestureRecognizer:tap];
                    
                }
                giftCell.messageModel = model;
                NSDictionary *dic =  model.message.ext;
                BOOL isReceiver = !model.isSender;
                //                NSString *imageName;
                //                if([model.message.to isEqualToString:self.chatUser.objectId]){
                //                    imageName =   BUBBLE_RIGHT_IMAGE_NAME;
                //                }else{
                //                    imageName = BUBBLE_LEFT_IMAGE_NAME;
                //                }
                NSString *imageName = isReceiver ? kChat_Gitf_Receiver_Bg : kChat_Gift_Sender_Bg;
                NSInteger leftCapWidth = isReceiver?BUBBLE_LEFT_LEFT_CAP_WIDTH:BUBBLE_RIGHT_LEFT_CAP_WIDTH;
                NSInteger topCapHeight =  isReceiver?BUBBLE_LEFT_TOP_CAP_HEIGHT:BUBBLE_RIGHT_TOP_CAP_HEIGHT;
                giftCell.giftBackgroudImageView.image = [[UIImage imageNamed:imageName] stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
                [giftCell.giftImageView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"giftImg"]] placeholderImage:[UIImage imageNamed:@"chat_gift_icon"]];
                giftCell.giftNameLabel.text = [dic objectForKey:@"giftName"];
                giftCell.giftInfoLabel.text = [dic objectForKey:@"giftInfo"];
                return giftCell;
            }
            
            
            
            NSString *cellIdentifier = [EMChatViewCell cellIdentifierForMessageModel:model];
            EMChatViewCell *cell = (EMChatViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[EMChatViewCell alloc] initWithMessageModel:model reuseIdentifier:cellIdentifier];
                cell.backgroundColor = [UIColor clearColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            if ([[model.message.ext objectForKey:@"type"]isEqualToString:EMMESSAGE_EXT_TYPE_BURN_AFTER_READ_MSG]){
                //                cell.bubbleView.frame=CGRectMake(0, 0, DeviceWidth, 40);
                //私密消息
                cell.BurnAfterRreadingLabel.hidden = NO;
                cell.bubbleView.userInteractionEnabled = YES;
                [cell.bubbleView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Burnafterreading:)]];
                
            }
            if ([self.title isEqualToString:@"无独团"]) {
                [cell.hasReadImage removeFromSuperview];
            }
            
            if (model.isSender) {
                MLUser *currentUser = [MLUser currentUser];
                model.nickName = currentUser.nickname;
                
                
                if (!currentUser.subAvatar || [currentUser.subAvatar isEqualToString:@""]) {
                    model.headImageURL = [NSURL URLWithString:currentUser.avatar.url];
                }else{
                    model.headImageURL = [NSURL URLWithString:currentUser.subAvatar];
                }
                
                
                UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapUserHeadImage)];
                [cell.headImageView addGestureRecognizer:tap];
            } else {
                model.nickName = self.chatUser.nickname;
                if (self.chatUser.avatar.url||self.chatUser.subAvatar){
                    
                    if (!self.chatUser.subAvatar || [self.chatUser.subAvatar isEqualToString:@""]) {
                        model.headImageURL = [NSURL URLWithString:self.chatUser.avatar.url];
                    }else{
                        model.headImageURL = [NSURL URLWithString:self.chatUser.subAvatar];
                    }
                }
                UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapChatHeadImage)];
                [cell.headImageView addGestureRecognizer:tap];
                
            }
            cell.messageModel = model;
            return cell;
        }
    }
    
    return nil;
}
- (void)tapUserHeadImage
{
    [self lookUserData:[MLUser currentUser]];
}
- (void)tapChatHeadImage
{
    [self lookUserData:self.chatUser];
}


#pragma mark - Table view delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSObject *obj = [self.dataSource objectAtIndex:indexPath.row];
    if ([obj isKindOfClass:[NSString class]]) {
        return 40;
    }
    else{
        // TODO 小灰条计算高度
        MessageModel *model = (MessageModel *)obj;
        NSDictionary *ext = model.message.ext;
        if (ext && [[ext objectForKey:@"type"] isEqual: @EMMESSAGE_EXT_TYPE_CHAT_NOTIFICATION_MSG]) {
            
        }else if (ext && [[ext objectForKey:@"giftType"] isEqual: @EMMESSAGE_EXT_TYPE_GIFT_MSG]){
            return 90;
        }
        return [EMChatViewCell tableView:tableView heightForRowAtIndexPath:indexPath withObject:(MessageModel *)obj];
    }
}

#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_slimeView) {
        [_slimeView scrollViewDidScroll];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (_slimeView) {
        [_slimeView scrollViewDidEndDraging];
    }
}

#pragma mark - slimeRefresh delegate
//加载更多
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    _chatTagDate = nil;
    [self loadMoreMessages];
    [_slimeView endRefresh];
}

#pragma mark - GestureRecognizer

// 点击背景隐藏
-(void)keyBoardHidden
{
    [self.chatToolBar endEditing:YES];
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan && [self.dataSource count] > 0) {
        CGPoint location = [recognizer locationInView:self.tableView];
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
        id object = [self.dataSource objectAtIndex:indexPath.row];
        MessageModel *model = [self.dataSource objectAtIndex:indexPath.row];
        if ([object isKindOfClass:[MessageModel class]]) {
            EMChatViewCell *cell = (EMChatViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            
            
            if(cell){
                //   NSLog(@"======= %@",model.message.ext);
                NSDictionary *ext =  model.message.ext;
                if (!ext &&! [[ext objectForKey:@"type"] isEqual:@1])
                {
                    [cell becomeFirstResponder];
                    _longPressIndexPath = indexPath;
                    [self showMenuViewController:cell.bubbleView andIndexPath:indexPath messageType:cell.messageModel.type];
                }
            }
            
            
            //            cell.messageModel.message.ext
            
        }
    }
}

-(void)Burnafterreading:(UITapGestureRecognizer *)recognizer
{
    if (burnafterreadingLook == YES) {
        [HUD Prompt:@"请先看完当前的私密消息"];
        return;
    }
    if ([self.dataSource count] > 0) {
        burnafterreadingLook = YES;
        CGPoint location = [recognizer locationInView:self.tableView];
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
        id object = [self.dataSource objectAtIndex:indexPath.row];
        if ([object isKindOfClass:[MessageModel class]]) {
            EMChatViewCell *cell = (EMChatViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            [cell becomeFirstResponder];
            [cell.BurnAfterRreadingLabel setHidden:YES];
            
            _longPressIndexPath = indexPath;
            __weak ChatViewController *weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf deleteMenuAction:nil];
                burnafterreadingLook = NO;
            });
            
        }
    }
}


- (void)reloadData{
    _chatTagDate = nil;
    self.dataSource = [[self formatMessages:self.messages] mutableCopy];
    [self.tableView reloadData];
    
    //回到前台时
    if (!self.isInvisible)
    {
        NSMutableArray *unreadMessages = [NSMutableArray array];
        for (EMMessage *message in self.messages)
        {
            if ([self shouldAckMessage:message read:NO])
            {
                [unreadMessages addObject:message];
            }
        }
        if ([unreadMessages count])
        {
            [self sendHasReadResponseForMessages:unreadMessages];
        }
        
        [_conversation markAllMessagesAsRead:YES];
    }
}

#pragma mark - UIResponder actions

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo
{
    MessageModel *model = [userInfo objectForKey:KMESSAGEKEY];
    if ([eventName isEqualToString:kRouterEventTextURLTapEventName]) {
        [self chatTextCellUrlPressed:[userInfo objectForKey:@"url"]];
    }
    else if ([eventName isEqualToString:kRouterEventAudioBubbleTapEventName]) {
        [self chatAudioCellBubblePressed:model];
    }
    else if ([eventName isEqualToString:kRouterEventImageBubbleTapEventName]){
        [self chatImageCellBubblePressed:model];
    }
    else if ([eventName isEqualToString:kRouterEventLocationBubbleTapEventName]){
        [self chatLocationCellBubblePressed:model];
    }
    else if([eventName isEqualToString:kResendButtonTapEventName]){
        EMChatViewCell *resendCell = [userInfo objectForKey:kShouldResendCell];
        MessageModel *messageModel = resendCell.messageModel;
        if ((messageModel.status != eMessageDeliveryState_Failure) && (messageModel.status != eMessageDeliveryState_Pending))
        {
            return;
        }
        id <IChatManager> chatManager = [[EaseMob sharedInstance] chatManager];
        [chatManager asyncResendMessage:messageModel.message progress:nil];
        NSIndexPath *indexPath = [self.tableView indexPathForCell:resendCell];
        [self.tableView beginUpdates];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath]
                              withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
    }else if([eventName isEqualToString:kRouterEventChatCellVideoTapEventName]){
        [self chatVideoCellPressed:model];
    }
}

//链接被点击
- (void)chatTextCellUrlPressed:(NSURL *)url
{
    if (url) {
        //        [[UIApplication sharedApplication] openURL:url];
        WEBViewController *webview = [[WEBViewController alloc]init];
        webview.WEBURL = [url absoluteString];
        [self.navigationController pushViewController:webview animated:YES];
    }
}

// 语音的bubble被点击
-(void)chatAudioCellBubblePressed:(MessageModel *)model
{
    id <IEMFileMessageBody> body = [model.message.messageBodies firstObject];
    EMAttachmentDownloadStatus downloadStatus = [body attachmentDownloadStatus];
    if (downloadStatus == EMAttachmentDownloading) {
        [self showHint:NSLocalizedString(@"message.downloadingAudio", @"downloading voice, click later")];
        return;
    }
    else if (downloadStatus == EMAttachmentDownloadFailure)
    {
        [self showHint:NSLocalizedString(@"message.downloadingAudio", @"downloading voice, click later")];
        [[EaseMob sharedInstance].chatManager asyncFetchMessage:model.message progress:nil];
        return;
    }
    // 播放音频
    if (model.type == eMessageBodyType_Voice) {
        //发送已读回执
        if ([self shouldAckMessage:model.message read:YES])
        {
            [self sendHasReadResponseForMessages:@[model.message]];
        }
        __weak ChatViewController *weakSelf = self;
        BOOL isPrepare = [self.messageReadManager prepareMessageAudioModel:model updateViewCompletion:^(MessageModel *prevAudioModel, MessageModel *currentAudioModel) {
            if (prevAudioModel || currentAudioModel) {
                [weakSelf.tableView reloadData];
            }
        }];
        
        if (isPrepare) {
            _isPlayingAudio = YES;
            __weak ChatViewController *weakSelf = self;
            [[EMCDDeviceManager sharedInstance] enableProximitySensor];
            [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:model.chatVoice.localPath completion:^(NSError *error) {
                [weakSelf.messageReadManager stopMessageAudioModel];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView reloadData];
                    weakSelf.isPlayingAudio = NO;
                    [[EMCDDeviceManager sharedInstance] disableProximitySensor];
                });
            }];
        }
        else{
            _isPlayingAudio = NO;
        }
    }
}

// 位置的bubble被点击
-(void)chatLocationCellBubblePressed:(MessageModel *)model
{
    _isScrollToBottom = NO;
    LocationViewController *locationController = [[LocationViewController alloc] initWithLocation:CLLocationCoordinate2DMake(model.latitude, model.longitude)];
    [self.navigationController pushViewController:locationController animated:YES];
}

- (void)chatVideoCellPressed:(MessageModel *)model{
    EMVideoMessageBody *videoBody = (EMVideoMessageBody*)model.messageBody;
    if (videoBody.attachmentDownloadStatus == EMAttachmentDownloadSuccessed)
    {
        NSString *localPath = model.message == nil ? model.localPath : [[model.message.messageBodies firstObject] localPath];
        if (localPath && localPath.length > 0)
        {
            //发送已读回执
            if ([self shouldAckMessage:model.message read:YES])
            {
                [self sendHasReadResponseForMessages:@[model.message]];
            }
            [self playVideoWithVideoPath:localPath viewcontroller:self];
            return;
        }
    }
    
    __weak ChatViewController *weakSelf = self;
    id <IChatManager> chatManager = [[EaseMob sharedInstance] chatManager];
    [weakSelf showHudInView:weakSelf.view hint:NSLocalizedString(@"message.downloadingVideo", @"downloading video...")];
    [chatManager asyncFetchMessage:model.message progress:nil completion:^(EMMessage *aMessage, EMError *error) {
        [weakSelf hideHud];
        if (!error) {
            //发送已读回执
            if ([weakSelf shouldAckMessage:model.message read:YES])
            {
                [weakSelf sendHasReadResponseForMessages:@[model.message]];
            }
            NSString *localPath = aMessage == nil ? model.localPath : [[aMessage.messageBodies firstObject] localPath];
            if (localPath && localPath.length > 0) {
                [weakSelf playVideoWithVideoPath:localPath viewcontroller:weakSelf];
            }
        }else{
            [weakSelf showHint:NSLocalizedString(@"message.videoFail", @"video for failure!")];
        }
    } onQueue:nil];
    
}

- (void)playVideoWithVideoPath:(NSString *)videoPath viewcontroller:(ChatViewController *)viewController
{
    _isScrollToBottom = NO;
    NSURL *videoURL = [NSURL fileURLWithPath:videoPath];
    MPMoviePlayerViewController *moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
    [moviePlayerController.moviePlayer prepareToPlay];
    moviePlayerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [viewController presentMoviePlayerViewControllerAnimated:moviePlayerController];
}

// 图片的bubble被点击
-(void)chatImageCellBubblePressed:(MessageModel *)model
{
    __weak ChatViewController *weakSelf = self;
    id <IChatManager> chatManager = [[EaseMob sharedInstance] chatManager];
    if ([model.messageBody messageBodyType] == eMessageBodyType_Image) {
        EMImageMessageBody *imageBody = (EMImageMessageBody *)model.messageBody;
        if (imageBody.thumbnailDownloadStatus == EMAttachmentDownloadSuccessed) {
            if (imageBody.attachmentDownloadStatus == EMAttachmentDownloadSuccessed)
            {
                //发送已读回执
                if ([self shouldAckMessage:model.message read:YES])
                {
                    [self sendHasReadResponseForMessages:@[model.message]];
                }
                NSString *localPath = model.message == nil ? model.localPath : [[model.message.messageBodies firstObject] localPath];
                if (localPath && localPath.length > 0) {
                    UIImage *image = [UIImage imageWithContentsOfFile:localPath];
                    self.isScrollToBottom = NO;
                    if (image)
                    {
                        [self.messageReadManager showBrowserWithImages:@[image]];
                    }
                    else
                    {
                        NSLog(@"Read %@ failed!", localPath);
                    }
                    return ;
                }
            }
            [weakSelf showHudInView:weakSelf.view hint:NSLocalizedString(@"message.downloadingImage", @"downloading a image...")];
            [chatManager asyncFetchMessage:model.message progress:nil completion:^(EMMessage *aMessage, EMError *error) {
                [weakSelf hideHud];
                if (!error) {
                    //发送已读回执
                    if ([weakSelf shouldAckMessage:model.message read:YES])
                    {
                        [weakSelf sendHasReadResponseForMessages:@[model.message]];
                    }
                    NSString *localPath = aMessage == nil ? model.localPath : [[aMessage.messageBodies firstObject] localPath];
                    if (localPath && localPath.length > 0) {
                        UIImage *image = [UIImage imageWithContentsOfFile:localPath];
                        weakSelf.isScrollToBottom = NO;
                        if (image)
                        {
                            [weakSelf.messageReadManager showBrowserWithImages:@[image]];
                        }
                        else
                        {
                            NSLog(@"Read %@ failed!", localPath);
                        }
                        return ;
                    }
                }
                [weakSelf showHint:NSLocalizedString(@"message.imageFail", @"image for failure!")];
            } onQueue:nil];
        }else{
            //获取缩略图
            [chatManager asyncFetchMessageThumbnail:model.message progress:nil completion:^(EMMessage *aMessage, EMError *error) {
                if (!error) {
                    [weakSelf reloadTableViewDataWithMessage:model.message];
                }else{
                    [weakSelf showHint:NSLocalizedString(@"message.thumImageFail", @"thumbnail for failure!")];
                }
                
            } onQueue:nil];
        }
    }else if ([model.messageBody messageBodyType] == eMessageBodyType_Video) {
        //获取缩略图
        EMVideoMessageBody *videoBody = (EMVideoMessageBody *)model.messageBody;
        if (videoBody.thumbnailDownloadStatus != EMAttachmentDownloadSuccessed) {
            [chatManager asyncFetchMessageThumbnail:model.message progress:nil completion:^(EMMessage *aMessage, EMError *error) {
                if (!error) {
                    [weakSelf reloadTableViewDataWithMessage:model.message];
                }else{
                    [weakSelf showHint:NSLocalizedString(@"message.thumImageFail", @"thumbnail for failure!")];
                }
            } onQueue:nil];
        }
    }
}

#pragma mark - IChatManagerDelegate

-(void)didSendMessage:(EMMessage *)message error:(EMError *)error
{
    //发送消息
    [self.dataSource enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         if ([obj isKindOfClass:[MessageModel class]])
         {
             MessageModel *model = (MessageModel*)obj;
             if ([model.messageId isEqualToString:message.messageId])
             {
                 model.message.deliveryState = message.deliveryState;
                 *stop = YES;
             }
         }
     }];
    [self.tableView reloadData];
}

- (void)didReceiveHasReadResponse:(EMReceipt*)receipt
{
    [self.dataSource enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         if ([obj isKindOfClass:[MessageModel class]])
         {
             MessageModel *model = (MessageModel*)obj;
             if ([model.messageId isEqualToString:receipt.chatId])
             {
                 model.message.isReadAcked = YES;
                 *stop = YES;
             }
         }
     }];
    [self.tableView reloadData];
}

- (void)reloadTableViewDataWithMessage:(EMMessage *)message{
    __weak ChatViewController *weakSelf = self;
    dispatch_async(_messageQueue, ^{
        if ([weakSelf.conversation.chatter isEqualToString:message.conversationChatter])
        {
            for (int i = 0; i < weakSelf.dataSource.count; i ++) {
                id object = [weakSelf.dataSource objectAtIndex:i];
                if ([object isKindOfClass:[MessageModel class]]) {
                    MessageModel *model = (MessageModel *)object;
                    if ([message.messageId isEqualToString:model.messageId]) {
                        MessageModel *cellModel = [MessageModelManager modelWithMessage:message];
                        if ([weakSelf.delelgate respondsToSelector:@selector(nickNameWithChatter:)]) {
                            NSString *showName = [weakSelf.delelgate nickNameWithChatter:model.username];
                            cellModel.nickName = showName?showName:cellModel.username;
                        }else {
                            cellModel.nickName = cellModel.username;
                        }
                        
                        if ([weakSelf.delelgate respondsToSelector:@selector(avatarWithChatter:)]) {
                            cellModel.headImageURL = [NSURL URLWithString:[weakSelf.delelgate avatarWithChatter:cellModel.username]];
                        }
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf.tableView beginUpdates];
                            [weakSelf.dataSource replaceObjectAtIndex:i withObject:cellModel];
                            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                            [weakSelf.tableView endUpdates];
                        });
                        break;
                    }
                }
            }
        }
    });
}

- (void)didMessageAttachmentsStatusChanged:(EMMessage *)message error:(EMError *)error{
    if (!error) {
        id<IEMFileMessageBody>fileBody = (id<IEMFileMessageBody>)[message.messageBodies firstObject];
        if ([fileBody messageBodyType] == eMessageBodyType_Image) {
            EMImageMessageBody *imageBody = (EMImageMessageBody *)fileBody;
            if ([imageBody thumbnailDownloadStatus] == EMAttachmentDownloadSuccessed)
            {
                [self reloadTableViewDataWithMessage:message];
            }
        }else if([fileBody messageBodyType] == eMessageBodyType_Video){
            EMVideoMessageBody *videoBody = (EMVideoMessageBody *)fileBody;
            if ([videoBody thumbnailDownloadStatus] == EMAttachmentDownloadSuccessed)
            {
                [self reloadTableViewDataWithMessage:message];
            }
        }else if([fileBody messageBodyType] == eMessageBodyType_Voice){
            if ([fileBody attachmentDownloadStatus] == EMAttachmentDownloadSuccessed)
            {
                [self reloadTableViewDataWithMessage:message];
            }
        }
    }else{
        
    }
}

- (void)didFetchingMessageAttachments:(EMMessage *)message progress:(float)progress{
    NSLog(@"didFetchingMessageAttachment: %f", progress);
}

-(void)didReceiveMessage:(EMMessage *)message
{
    id<IEMMessageBody> messageBody = message.messageBodies.lastObject;
    
    if (messageBody.message.ext != nil) {
        if ([[messageBody.message.ext objectForKey:@"notification"]isEqualToString:EMMESSAGE_EXT_NOTI_CALL_APPLY_ACCEPTED]){
            //未读的震动
            if (!messageBody.message.isRead) {
                //[Utils Hidden:self.attachView Bool:NO];
            }
        }
    }
    
    
    if ([_conversation.chatter isEqualToString:message.conversationChatter]) {
        
        //是对方发过来的消息
        [self addMessage:message];
        if ([self shouldAckMessage:message read:NO])
        {
            [self sendHasReadResponseForMessages:@[message]];
        }
        if ([self shouldMarkMessageAsRead])
        {
            [self markMessagesAsRead:@[message]];
        }
        //[self sendHasReadResponseForMessages:@[message]];
    }
}



- (void)didReceiveMessageId:(NSString *)messageId
                    chatter:(NSString *)conversationChatter
                      error:(EMError *)error
{
    if (error && [_conversation.chatter isEqualToString:conversationChatter]) {
        
        __weak ChatViewController *weakSelf = self;
        for (int i = 0; i < self.dataSource.count; i ++) {
            id object = [self.dataSource objectAtIndex:i];
            if ([object isKindOfClass:[MessageModel class]]) {
                MessageModel *currentModel = [self.dataSource objectAtIndex:i];
                EMMessage *currMsg = [currentModel message];
                if ([messageId isEqualToString:currMsg.messageId]) {
                    currMsg.deliveryState = eMessageDeliveryState_Failure;
                    MessageModel *cellModel = [MessageModelManager modelWithMessage:currMsg];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.tableView beginUpdates];
                        [weakSelf.dataSource replaceObjectAtIndex:i withObject:cellModel];
                        [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                        [weakSelf.tableView endUpdates];
                        
                    });
                    
                    break;
                }
            }
        }
    }
}

- (void)didFinishedReceiveOfflineMessages:(NSArray *)offlineMessages
{
    if ([self shouldMarkMessageAsRead])
    {
        [_conversation markAllMessagesAsRead:YES];
    }
    if (![offlineMessages count])
    {
        return;
    }
    _chatTagDate = nil;
    [self loadMoreMessages];
    __weak typeof(self) weakSelf = self;
    dispatch_async(_messageQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf scrollViewToBottom:NO];
        });
    });
    
}

- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages
{
    if (![offlineMessages count])
    {
        return;
    }
    if ([self shouldMarkMessageAsRead])
    {
        [_conversation markAllMessagesAsRead:YES];
    }
    _chatTagDate = nil;
    [self loadMoreMessages];
    __weak typeof(self) weakSelf = self;
    dispatch_async(_messageQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf scrollViewToBottom:NO];
        });
    });
}

- (void)group:(EMGroup *)group didLeave:(EMGroupLeaveReason)reason error:(EMError *)error
{
    if (_isChatGroup && [group.groupId isEqualToString:_chatter]) {
        [self.navigationController popToViewController:self animated:NO];
        [self.navigationController popViewControllerAnimated:NO];
    }
}

- (void)didInterruptionRecordAudio
{
    [_chatToolBar cancelTouchRecord];
    
    // 设置当前conversation的所有message为已读
    [_conversation markAllMessagesAsRead:YES];
    
    [self stopAudioPlayingWithChangeCategory:YES];
}

- (void)groupDidUpdateInfo:(EMGroup *)group error:(EMError *)error
{
    if (!error && _isChatGroup && [_chatter isEqualToString:group.groupId])
    {
        
    }
}


#pragma mark - IChatManagerDelegate 登录状态变化

- (void)didLoginFromOtherDevice
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes firstObject] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

- (void)didRemovedFromServer
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes firstObject] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

#pragma mark - EMChatBarMoreViewDelegate

- (void)moreViewPhotoAction:(DXChatBarMoreView *)moreView
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"isShowPicker"];
    // 隐藏键盘
    [self keyBoardHidden];
    
    // 弹出照片选择
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
    self.isInvisible = YES;
}

- (void)moreViewTakePicAction:(DXChatBarMoreView *)moreView
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"isShowPicker"];
    [self keyBoardHidden];
    
#if TARGET_IPHONE_SIMULATOR
    [self showHint:NSLocalizedString(@"message.simulatorNotSupportCamera", @"simulator does not support taking picture")];
#elif TARGET_OS_IPHONE
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
    self.isInvisible = YES;
#endif
}
//礼物
- (void)moreViewGiftAction:(DXChatBarMoreView *)moreView;
{
    if(_chatUser){
        GiftViewController *giftVC = [[GiftViewController alloc] init];
        giftVC.title = [NSString stringWithFormat:@"送%@小礼物",_chatUser.nickname];
        giftVC.chatter = _chatUser.objectId;
        [Utils pushTabbarHidden:giftVC Selfvc:self];
    }else if([self.title isEqualToString:@"无独团"]){
        [HUD Prompt:@"通知暂不支持此功能"];
    }else{
        if (self.isNullChatUser) {
            [HUD Prompt:@"正在加载对方信息,请稍后"];
        }else{
            [HUD Prompt:@"错误"];
        }
    }
}
- (void)moreViewLocationAction:(DXChatBarMoreView *)moreView
{
    // 隐藏键盘
    [self keyBoardHidden];
    
    LocationViewController *locationController = [[LocationViewController alloc] initWithNibName:nil bundle:nil];
    locationController.delegate = self;
    [self.navigationController pushViewController:locationController animated:YES];
}

- (void)moreViewVideoAction:(DXChatBarMoreView *)moreView
{
    if(_chatUser){
         [[NSNotificationCenter defaultCenter] postNotificationName:@"callOutWithChatter" object:@{@"chatter":self.chatter, @"chatUser":_chatUser, @"type":[NSNumber numberWithInt:eCallSessionTypeVideo]}];
    }
    //  [ShareData shareData].callVC = self;
}
//打电话
- (void)callUp
{
    
    
    [self keyBoardHidden];
    __weak ChatViewController *weakSelf = self;
    
    if (_chatUser) {
        [_chatUser refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            
            [AVAnalytics event:[NSString stringWithFormat:@"聊天百宝箱功能"] label:@"打电话"]; //type是变量,表示用户类型
            if (!error) {
                BOOL isSponsor = NO;
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"callOutWithChatter" object:@{@"chatter":weakSelf.chatter, @"chatUser":weakSelf.chatUser, @"type":[NSNumber numberWithInt:eCallSessionTypeAudio],@"isSponsor":[NSNumber numberWithBool:isSponsor]}];
            }else{
                [HUD Prompt:@"操作错误，请重新尝试"];
            }
            
        }];
    }else{
        [HUD Prompt:@"正在加载对方信息,请稍后"];
    }
    
   
    
}
- (void)moreViewAudioCallAction:(DXChatBarMoreView *)moreView
{
    // 隐藏键盘
    
    [self callUp];
}

/*附加
 */

//私密消息
- (void)moreViewPrivateMessagesAction:(DXChatBarMoreView *)moreView
{
    //阅后即焚
    _chatToolBar.burnAfterReading_Bool = YES;
    [_chatToolBar.styleChangeButton setImage:[UIImage imageNamed:@"reciprocal_icon"] forState:UIControlStateNormal];
    
}

//戳一下
- (void)moreViewJitterAction:(DXChatBarMoreView *)moreView
{
    if (self.vibrationNumber >= 44) {
        [HUD Prompt:@"您的操作过快，请等待..."];
        // 隐藏键盘
        [self keyBoardHidden];
        return;
    }
    if (self.vibrationNumber >= 1) {
        __weak ChatViewController *weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.vibrationNumber = 0;
        });
    }
    
    NSDictionary *ext = @{@"notification": EMMESSAGE_EXT_TYPE_JITTER_APPLY};
    [self sendTextMessageWithExt:self.PromptArr[random()%self.PromptArr.count+0] ext:ext];
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    self.vibrationNumber++;
    [HUD shakeAnimationForView:self.view.window];
    
    static SystemSoundID soundIDTest = 0;
    
    NSString * path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"wav"];
    if (path) {
        AudioServicesCreateSystemSoundID( (__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundIDTest );
    }
    AudioServicesPlaySystemSound( soundIDTest );
    
    
}
//我睡了
- (void)moreViewSleepAction:(DXChatBarMoreView *)moreView
{
    
}
//真心话
- (void)moreViewTruthAction:(DXChatBarMoreView *)moreView
{
    
}

#pragma mark - LocationViewDelegate
-(void)sendLocationLatitude:(double)latitude longitude:(double)longitude andAddress:(NSString *)address
{
    EMMessage *locationMessage = [ChatSendHelper sendLocationLatitude:latitude longitude:longitude address:address toUsername:_conversation.chatter messageType:[self messageType] requireEncryption:NO ext:nil];
    [self addMessage:locationMessage];
}

#pragma mark - DXMessageToolBarDelegate
- (void)inputTextViewWillBeginEditing:(XHMessageTextView *)messageInputTextView{
    
    [_menuController setMenuItems:nil];
}
- (void)didChangeFrameToHeight:(CGFloat)toHeight
{
    __weak ChatViewController *weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = weakSelf.tableView.frame;
        rect.origin.y = 0;
        rect.size.height = weakSelf.view.frame.size.height - toHeight;
        weakSelf.tableView.frame = rect;
    }];
    [self scrollViewToBottom:NO];
}

- (void)didSendText:(UITextView *)textView
{
    if (textView.text && textView.text.length > 0) {
        [self sendTextMessage:textView];
    }
}

/**
 *  按下录音按钮开始录音
 */
- (void)didStartRecordingVoiceAction:(UIView *)recordView
{
    if ([self canRecord]) {
        DXRecordView *tmpView = (DXRecordView *)recordView;
        tmpView.center = self.view.center;
        [self.view addSubview:tmpView];
        [self.view bringSubviewToFront:recordView];
        int x = arc4random() % 100000;
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
        
        [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName
                                                                 completion:^(NSError *error)
         {
             if (error) {
                 NSLog(NSLocalizedString(@"message.startRecordFail", @"failure to start recording"));
             }
         }];
    }
}

/**
 *  手指向上滑动取消录音
 */
- (void)didCancelRecordingVoiceAction:(UIView *)recordView
{
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
}

/**
 *  松开手指完成录音
 */
- (void)didFinishRecoingVoiceAction:(UIView *)recordView
{
    __weak typeof(self) weakSelf = self;
    [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
        if (!error) {
            EMChatVoice *voice = [[EMChatVoice alloc] initWithFile:recordPath
                                                       displayName:@"audio"];
            voice.duration = aDuration;
            [weakSelf sendAudioMessage:voice];
        }else {
            [weakSelf showHudInView:self.view hint:@"录音时间太短了"];
            weakSelf.chatToolBar.recordButton.enabled = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf hideHud];
                weakSelf.chatToolBar.recordButton.enabled = YES;
            });
        }
    }];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSURL *videoURL = info[UIImagePickerControllerMediaURL];
        [picker dismissViewControllerAnimated:YES completion:^{
            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"isShowPicker"];
        }];
        // video url:
        // file:///private/var/mobile/Applications/B3CDD0B2-2F19-432B-9CFA-158700F4DE8F/tmp/capture-T0x16e39100.tmp.9R8weF/capturedvideo.mp4
        // we will convert it to mp4 format
        NSURL *mp4 = [self convert2Mp4:videoURL];
        NSFileManager *fileman = [NSFileManager defaultManager];
        if ([fileman fileExistsAtPath:videoURL.path]) {
            NSError *error = nil;
            [fileman removeItemAtURL:videoURL error:&error];
            if (error) {
                NSLog(@"failed to remove file, error:%@.", error);
            }
        }
        EMChatVideo *chatVideo = [[EMChatVideo alloc] initWithFile:[mp4 relativePath] displayName:@"video.mp4"];
        [self sendVideoMessage:chatVideo];
        
    }else{
        UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
        [picker dismissViewControllerAnimated:YES completion:^{
            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"isShowPicker"];
        }];
        [self sendImageMessage:orgImage];
    }
    self.isInvisible = NO;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"isShowPicker"];
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - MenuItem actions

- (void)copyMenuAction:(id)sender
{
    // todo by du. 复制
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (_longPressIndexPath.row > 0) {
        MessageModel *model = [self.dataSource objectAtIndex:_longPressIndexPath.row];
        pasteboard.string = model.content;
    }
    
    _longPressIndexPath = nil;
}

- (void)deleteMenuAction:(id)sender
{
    if (_longPressIndexPath && _longPressIndexPath.row > 0) {
        MessageModel *model = [self.dataSource objectAtIndex:_longPressIndexPath.row];
        NSMutableIndexSet *indexs = [NSMutableIndexSet indexSetWithIndex:_longPressIndexPath.row];
        [_conversation removeMessage:model.message];
        NSMutableArray *indexPaths = [NSMutableArray arrayWithObjects:_longPressIndexPath, nil];;
        if (_longPressIndexPath.row - 1 >= 0) {
            id nextMessage = nil;
            id prevMessage = [self.dataSource objectAtIndex:(_longPressIndexPath.row - 1)];
            if (_longPressIndexPath.row + 1 < [self.dataSource count]) {
                nextMessage = [self.dataSource objectAtIndex:(_longPressIndexPath.row + 1)];
            }
            if ((!nextMessage || [nextMessage isKindOfClass:[NSString class]]) && [prevMessage isKindOfClass:[NSString class]]) {
                [indexs addIndex:_longPressIndexPath.row - 1];
                [indexPaths addObject:[NSIndexPath indexPathForRow:(_longPressIndexPath.row - 1) inSection:0]];
            }
        }
        
        [self.dataSource removeObjectsAtIndexes:indexs];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
    }
    
    _longPressIndexPath = nil;
}

#pragma mark - private

- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    return bCanRecord;
}

- (void)stopAudioPlayingWithChangeCategory:(BOOL)isChange
{
    //停止音频播放及播放动画
    [[EMCDDeviceManager sharedInstance] stopPlaying];
    [[EMCDDeviceManager sharedInstance] disableProximitySensor];
    [EMCDDeviceManager sharedInstance].delegate = nil;
    MessageModel *playingModel = [self.messageReadManager stopMessageAudioModel];
    NSIndexPath *indexPath = nil;
    if (playingModel) {
        indexPath = [NSIndexPath indexPathForRow:[self.dataSource indexOfObject:playingModel] inSection:0];
    }
    
    if (indexPath) {
        __weak ChatViewController *weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView beginUpdates];
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [weakSelf.tableView endUpdates];
        });
    }
}

- (void)loadMoreMessages
{
    __weak typeof(self) weakSelf = self;
    dispatch_async(_messageQueue, ^{
        long long timestamp = [[NSDate date] timeIntervalSince1970] * 1000 + 1;
        
        NSArray *messages = [weakSelf.conversation loadNumbersOfMessages:([weakSelf.messages count] + KPageCount) before:timestamp];
        if ([messages count] > 0) {
            weakSelf.messages = [messages mutableCopy];
            
            NSInteger currentCount = [weakSelf.dataSource count];
            weakSelf.dataSource = [[weakSelf formatMessages:messages] mutableCopy];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                NSInteger row = [weakSelf.dataSource count] - currentCount - 1;
                
                if (row<=0) {
                    row = 0;
                }
                
                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
            });
            
            //从数据库导入时重新下载没有下载成功的附件
            for (NSInteger i = 0; i < [weakSelf.dataSource count]; i++)
            {
                id obj = weakSelf.dataSource[i];
                if ([obj isKindOfClass:[MessageModel class]])
                {
                    [weakSelf downloadMessageAttachments:obj];
                }
            }
            
            NSMutableArray *unreadMessages = [NSMutableArray array];
            for (NSInteger i = 0; i < [messages count]; i++)
            {
                EMMessage *message = messages[i];
                if ([weakSelf shouldAckMessage:message read:NO])
                {
                    [unreadMessages addObject:message];
                }
            }
            if ([unreadMessages count])
            {
                [weakSelf sendHasReadResponseForMessages:unreadMessages];
            }
        }
    });
}

- (void)downloadMessageAttachments:(MessageModel *)model
{
    __weak typeof(self) weakSelf = self;
    void (^completion)(EMMessage *aMessage, EMError *error) = ^(EMMessage *aMessage, EMError *error) {
        if (!error)
        {
            [weakSelf reloadTableViewDataWithMessage:model.message];
        }
        else
        {
            [weakSelf showHint:NSLocalizedString(@"message.thumImageFail", @"thumbnail for failure!")];
        }
    };
    
    if ([model.messageBody messageBodyType] == eMessageBodyType_Image) {
        EMImageMessageBody *imageBody = (EMImageMessageBody *)model.messageBody;
        if (imageBody.thumbnailDownloadStatus != EMAttachmentDownloadSuccessed)
        {
            //下载缩略图
            [[[EaseMob sharedInstance] chatManager] asyncFetchMessageThumbnail:model.message progress:nil completion:completion onQueue:nil];
        }
    }
    else if ([model.messageBody messageBodyType] == eMessageBodyType_Video)
    {
        EMVideoMessageBody *videoBody = (EMVideoMessageBody *)model.messageBody;
        if (videoBody.thumbnailDownloadStatus != EMAttachmentDownloadSuccessed)
        {
            //下载缩略图
            [[[EaseMob sharedInstance] chatManager] asyncFetchMessageThumbnail:model.message progress:nil completion:completion onQueue:nil];
        }
    }
    else if ([model.messageBody messageBodyType] == eMessageBodyType_Voice)
    {
        EMVoiceMessageBody *voiceBody = (EMVoiceMessageBody*)model.messageBody;
        if (voiceBody.attachmentDownloadStatus != EMAttachmentDownloadSuccessed)
        {
            //下载语言
            [[EaseMob sharedInstance].chatManager asyncFetchMessage:model.message progress:nil];
        }
    }
}

- (NSArray *)formatMessages:(NSArray *)messagesArray
{
    NSMutableArray *formatArray = [[NSMutableArray alloc] init];
    if ([messagesArray count] > 0) {
        for (EMMessage *message in messagesArray) {
            NSDate *createDate = [NSDate dateWithTimeIntervalInMilliSecondSince1970:(NSTimeInterval)message.timestamp];
            NSTimeInterval tempDate = [createDate timeIntervalSinceDate:self.chatTagDate];
            if (tempDate > 60 || tempDate < -60 || (self.chatTagDate == nil)) {
                [formatArray addObject:[createDate formattedTime]];
                self.chatTagDate = createDate;
            }
            
            MessageModel *model = [MessageModelManager modelWithMessage:message];
            if ([_delelgate respondsToSelector:@selector(nickNameWithChatter:)]) {
                NSString *showName = [_delelgate nickNameWithChatter:model.username];
                model.nickName = showName?showName:model.username;
            }else {
                model.nickName = model.username;
            }
            
            if ([_delelgate respondsToSelector:@selector(avatarWithChatter:)]) {
                model.headImageURL = [NSURL URLWithString:[_delelgate avatarWithChatter:model.username]];
            }
            
            if (model) {
                [formatArray addObject:model];
            }
        }
    }
    
    return formatArray;
    
}

-(NSMutableArray *)formatMessage:(EMMessage *)message
{
    NSMutableArray *ret = [[NSMutableArray alloc] init];
    NSDate *createDate = [NSDate dateWithTimeIntervalInMilliSecondSince1970:(NSTimeInterval)message.timestamp];
    NSTimeInterval tempDate = [createDate timeIntervalSinceDate:self.chatTagDate];
    if (tempDate > 60 || tempDate < -60 || (self.chatTagDate == nil)) {
        [ret addObject:[createDate formattedTime]];
        self.chatTagDate = createDate;
    }
    
    MessageModel *model = [MessageModelManager modelWithMessage:message];
    if ([_delelgate respondsToSelector:@selector(nickNameWithChatter:)]) {
        NSString *showName = [_delelgate nickNameWithChatter:model.username];
        model.nickName = showName?showName:model.username;
    }else {
        model.nickName = model.username;
    }
    
    if ([_delelgate respondsToSelector:@selector(avatarWithChatter:)]) {
        model.headImageURL = [NSURL URLWithString:[_delelgate avatarWithChatter:model.username]];
    }
    
    if (model) {
        [ret addObject:model];
    }
    
    return ret;
}

-(void)addMessage:(EMMessage *)message
{
    [_messages addObject:message];
    __weak ChatViewController *weakSelf = self;
    dispatch_async(_messageQueue, ^{
        NSArray *messages = [weakSelf formatMessage:message];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.dataSource addObjectsFromArray:messages];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[weakSelf.dataSource count] - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        });
    });
}

- (void)scrollViewToBottom:(BOOL)animated
{
    if (self.tableView.contentSize.height > self.tableView.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
        [self.tableView setContentOffset:offset animated:animated];
    }
}

- (void)showRoomContact:(id)sender
{
    [self.view endEditing:YES];
    if (self.conversationType == eConversationTypeGroupChat) {
        ChatGroupDetailViewController *detailController = [[ChatGroupDetailViewController alloc] initWithGroupId:_chatter];
        [self.navigationController pushViewController:detailController animated:YES];
    }
    else if (self.conversationType == eConversationTypeChatRoom)
    {
        FriendsViewController *detailController = [[FriendsViewController alloc] init];
        [self.navigationController pushViewController:detailController animated:YES];
    }
}


- (void)removeAllMessages:(id)sender
{
    if (_dataSource.count == 0) {
        [self showHint:NSLocalizedString(@"message.noMessage", @"no messages")];
        return;
    }
    
    if ([sender isKindOfClass:[NSNotification class]]) {
        NSString *groupId = (NSString *)[(NSNotification *)sender object];
        if (self.isChatGroup && [groupId isEqualToString:_conversation.chatter]) {
            [_conversation removeAllMessages];
            [_messages removeAllObjects];
            _chatTagDate = nil;
            [_dataSource removeAllObjects];
            [_tableView reloadData];
            [self showHint:NSLocalizedString(@"message.noMessage", @"no messages")];
        }
    }
    else{
        __weak typeof(self) weakSelf = self;
        
        [EMAlertView showAlertWithTitle:NSLocalizedString(@"prompt", @"Prompt")
                                message:NSLocalizedString(@"sureToDelete", @"please make sure to delete")
                        completionBlock:^(NSUInteger buttonIndex, EMAlertView *alertView) {
                            if (buttonIndex == 1) {
                                [weakSelf.conversation removeAllMessages];
                                [weakSelf.messages removeAllObjects];
                                weakSelf.chatTagDate = nil;
                                [weakSelf.dataSource removeAllObjects];
                                [weakSelf.tableView reloadData];
                            }
                        } cancelButtonTitle:NSLocalizedString(@"cancel", @"Cancel")
                      otherButtonTitles:NSLocalizedString(@"ok", @"OK"), nil];
    }
}

- (void)showMenuViewController:(UIView *)showInView andIndexPath:(NSIndexPath *)indexPath messageType:(MessageBodyType)messageType
{
    if (_menuController == nil) {
        _menuController = [UIMenuController sharedMenuController];
    }
    if (_copyMenuItem == nil) {
        _copyMenuItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"copy", @"Copy") action:@selector(copyMenuAction:)];
    }
    if (_deleteMenuItem == nil) {
        _deleteMenuItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"delete", @"Delete") action:@selector(deleteMenuAction:)];
    }
    
    if (messageType == eMessageBodyType_Text) {
        [_menuController setMenuItems:@[_copyMenuItem, _deleteMenuItem]];
    }
    else{
        [_menuController setMenuItems:@[_deleteMenuItem]];
    }
    
    [_menuController setTargetRect:showInView.frame inView:showInView.superview];
    [_menuController setMenuVisible:YES animated:YES];
}

- (void)exitGroup
{
    [self.navigationController popToViewController:self animated:NO];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)insertCallMessage:(NSNotification *)notification
{
    id object = notification.object;
    if (object) {
        EMMessage *message = (EMMessage *)object;
        
        if ([message.to isEqualToString:self.chatter]) {
            [self addMessage:message];
        }else if([message.to isEqualToString:@"mlsystem"]){
            if([self.title isEqualToString:@"无独团"]){
                [self addMessage:message];
            }
        }
    }
}
- (void)applicationDidEnterBackground
{
    [_chatToolBar cancelTouchRecord];
    
    // 设置当前conversation的所有message为已读
    [_conversation markAllMessagesAsRead:YES];
}

- (BOOL)shouldAckMessage:(EMMessage *)message read:(BOOL)read
{
    NSString *account = [[EaseMob sharedInstance].chatManager loginInfo][kSDKUsername];
    if (message.messageType != eMessageTypeChat || message.isReadAcked || [account isEqualToString:message.from] || ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) || _isInvisible)
    {
        return NO;
    }
    
    id<IEMMessageBody> body = [message.messageBodies firstObject];
    if (((body.messageBodyType == eMessageBodyType_Video) ||
         (body.messageBodyType == eMessageBodyType_Voice)) &&
        !read)
    {
        
        // ||        (body.messageBodyType == eMessageBodyType_Image)
        return NO;
    }
    else
    {
        return YES;
    }
}

- (BOOL)shouldMarkMessageAsRead
{
    if (([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) || self.isInvisible)
    {
        return NO;
    }
    
    return YES;
}

- (EMMessageType)messageType
{
    EMMessageType type = eMessageTypeChat;
    switch (_conversationType) {
        case eConversationTypeChat:
            type = eMessageTypeChat;
            break;
        case eConversationTypeGroupChat:
            type = eMessageTypeGroupChat;
            break;
        case eConversationTypeChatRoom:
            type = eMessageTypeChatRoom;
            break;
        default:
            break;
    }
    return type;
}

- (void)hideImagePicker
{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
    self.isInvisible = NO;
}
#pragma mark - send message

-(void)sendTextMessage:(UITextView *)textView
{
   
        
        //如果是阅后即焚
        if (_chatToolBar.burnAfterReading_Bool == YES) {
            NSDictionary *ext = @{@"type": EMMESSAGE_EXT_TYPE_BURN_AFTER_READ_MSG,@"time":@"3"};
            [self sendTextMessageWithExt:textView.text ext:ext];
        }else{
            EMMessage *tempMessage = [ChatSendHelper sendTextMessageWithString:textView.text
                                                                    toUsername:_conversation.chatter
                                                                   isChatGroup:_isChatGroup
                                                             requireEncryption:NO
                                                                           ext:nil];
            [self addMessage:tempMessage];
        }
        textView.text = @"";
    
}
//插入一个小灰条,只能本人看到
- (void)interpositionMessageText:(NSString *)text
{
    NSDictionary *ext = @{@"type": @EMMESSAGE_EXT_TYPE_CHAT_NOTIFICATION_MSG};
    //NSString *msg = [NSString stringWithFormat:@"我正在给你发消息"];
    EMChatText *txt = [[EMChatText alloc] initWithText:text];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txt];
    EMMessage *message = [[EMMessage alloc] initWithReceiver:_conversation.chatter bodies:@[body]];
    message.ext = ext;
    message.isRead = YES;
    message.messageType = eMessageTypeChat; // 设置为单聊消息
    message.deliveryState = eMessageDeliveryState_Delivered;
    [[EaseMob sharedInstance].chatManager insertMessageToDB:message];
    [self addMessage:message];
}

#pragma mark在所有的发送出去的方法里面加上判断,决定是否要发送成功

//发送短信
- (void)sendPhoneUser:(MLUser *)chatUser type:(NSNumber *)type
{
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:chatUser.objectId, @"userId", nil];
    [AVCloud callFunctionInBackground:@"checkOnlineStatus" withParameters:dic block:^(id objectt, NSError *errorr) {
        NSString *str = (NSString *)objectt;
        if ([str isEqualToString:@"online"]) {
            //用户在线
            
        }else{
            
            if(chatUser.notifyPhoneNum&&chatUser.notifyPhoneNum.length>0){
                NSDictionary *phoneDic = [NSDictionary dictionaryWithObjectsAndKeys:chatUser.mobilePhoneNumber, @"phone",[MLUser currentUser].nickname, @"name",type,@"type", nil];
                [AVCloud callFunctionInBackground:@"sendSysSms" withParameters:phoneDic block:^(id object, NSError *error) {
                    
                }];
            }else if (chatUser.mobilePhoneNumber&&chatUser.mobilePhoneNumber.length>0) {
                //用户不在线
                NSDictionary *phoneDic = [NSDictionary dictionaryWithObjectsAndKeys:chatUser.mobilePhoneNumber, @"phone",[MLUser currentUser].nickname, @"name",type,@"type", nil];
                [AVCloud callFunctionInBackground:@"sendSysSms" withParameters:phoneDic block:^(id object, NSError *error) {
                    
                }];
            }
        }
    }];
    
    
    
}

// 发送带自定义扩展的消息
-(void)sendTextMessageWithExt:(NSString *)textMessage ext:(NSDictionary *)ext
{
   
        EMMessage *tempMessage = [ChatSendHelper sendTextMessageWithString:textMessage
                                                                toUsername:_conversation.chatter
                                                               isChatGroup:_isChatGroup
                                                         requireEncryption:NO
                                                                       ext:ext];
        [self addMessage:tempMessage];
    
    
    
}

-(void)sendImageMessage:(UIImage *)image
{
    
        EMMessage *tempMessage = [ChatSendHelper sendImageMessageWithImage:image
                                                                toUsername:_conversation.chatter
                                                               messageType:[self messageType]
                                                         requireEncryption:NO
                                                                       ext:nil];
        [self addMessage:tempMessage];
    
}

-(void)sendAudioMessage:(EMChatVoice *)voice
{
    
        EMMessage *tempMessage = [ChatSendHelper sendVoice:voice
                                                toUsername:_conversation.chatter
                                               messageType:[self messageType]
                                         requireEncryption:NO ext:nil];
        [self addMessage:tempMessage];
    
}

-(void)sendVideoMessage:(EMChatVideo *)video
{
   
        EMMessage *tempMessage = [ChatSendHelper sendVideo:video
                                                toUsername:_conversation.chatter
                                               messageType:[self messageType]
                                         requireEncryption:NO ext:nil];
        [self addMessage:tempMessage];
    
}

- (void)sendHasReadResponseForMessages:(NSArray*)messages
{
    //未读消息处理
    dispatch_async(_messageQueue, ^{
        for (EMMessage *message in messages)
        {
            if ([[message.ext objectForKey:@"notification"]isEqualToString:EMMESSAGE_EXT_TYPE_CALL_APPLY_ACCEPTED]){
                [Utils Hidden:headViewLabel Bool:YES];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [Utils Hidden:headViewLabel Bool:NO];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [headViewLabel removeFromSuperview];
                    });
                });
            }
            [[EaseMob sharedInstance].chatManager sendReadAckForMessage:message];
        }
    });
}

- (void)markMessagesAsRead:(NSArray*)messages
{
    EMConversation *conversation = _conversation;
    dispatch_async(_messageQueue, ^{
        for (EMMessage *message in messages)
        {
            [conversation markMessageWithId:message.messageId asRead:YES];
        }
    });
}

#pragma mark - EMCDDeviceManagerDelegate
- (void)proximitySensorChanged:(BOOL)isCloseToUser{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if (isCloseToUser)
    {
        [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    } else {
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        if (!_isPlayingAudio) {
            [[EMCDDeviceManager sharedInstance] disableProximitySensor];
        }
    }
    [audioSession setActive:YES error:nil];
}

#pragma mark - EMChatManagerChatroomDelegate

- (void)chatroom:(EMChatroom *)chatroom occupantDidJoin:(NSString *)username
{
    CGRect frame = self.chatToolBar.frame;
    [self showHint:[NSString stringWithFormat:@"%@加入%@", username, chatroom.chatroomId] yOffset:-frame.size.height + KHintAdjustY];
}

- (void)chatroom:(EMChatroom *)chatroom occupantDidLeave:(NSString *)username
{
    CGRect frame = self.chatToolBar.frame;
    [self showHint:[NSString stringWithFormat:@"%@离开%@", username, chatroom.chatroomId] yOffset:-frame.size.height + KHintAdjustY];
}

- (void)beKickedOutFromChatroom:(EMChatroom *)chatroom reason:(EMChatroomBeKickedReason)reason
{
    if ([_chatter isEqualToString:chatroom.chatroomId])
    {
        _isKicked = YES;
        CGRect frame = self.chatToolBar.frame;
        [self showHint:[NSString stringWithFormat:@"被踢出%@", chatroom.chatroomId] yOffset:-frame.size.height + KHintAdjustY];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - ICallManagerDelegate

- (void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error{
    if (reason == eCallReason_Null) {
        if ([[EMCDDeviceManager sharedInstance] isPlaying]) {
            [self stopAudioPlayingWithChangeCategory:NO];
        }
    }
}

#pragma mark - 创建带附件的消息体和批量导入消息的示例

#pragma mark - date apply action




- (void)launchVoipCall {
    // 发起首次VOIP电话
    // 标识约会成功
    [[NSNotificationCenter defaultCenter] postNotificationName:@"callOutWithChatter" object:@{@"chatter":self.chatter, @"chatUser":_chatUser, @"type":[NSNumber numberWithInt:eCallSessionTypeAudio]}];
    //[ShareData shareData].callVC = self;
    
}

@end
